在AngularJS中提交表单并使用浏览器的“记住密码”功能,并且在随后的登录尝试中让浏览器使用用户名和密码填写登录表单时,$scope模型不会根据自动填充进行更改。
我发现的唯一一个肮脏的方法是使用下面的指令:
app.directive("xsInputSync", ["$timeout" , function($timeout) {
return {
restrict : "A",
require: "?ngModel",
link : function(scope, element, attrs, ngModel) {
$timeout(function() {
if (ngModel.$viewValue && ngModel.$viewValue !== element.val()) {
scope.apply(function() {
ngModel.$setViewValue(element.val());
});
}
console.log(scope);
console.log(ngModel.$name);
console.log(scope[ngModel.$name]);
}, 3000);
}
};
}]);问题是ngModel.$setViewValue(element.val());不会根据element.val()返回值更改模型或视图。我如何才能做到这一点?
发布于 2013-11-08 16:28:13
您不需要使用$timeout或类似的东西。您可以使用事件系统。
我认为它更英国化,不依赖于jQuery或自定义事件捕获。
例如,在提交处理程序上:
$scope.doLogin = function() {
$scope.$broadcast("autofill:update");
// Continue with the login.....
};然后你可以有一个像这样的autofill指令:
.directive("autofill", function () {
return {
require: "ngModel",
link: function (scope, element, attrs, ngModel) {
scope.$on("autofill:update", function() {
ngModel.$setViewValue(element.val());
});
}
}
});最后,您的HTML将如下所示:
<input type="text" name="username" ng-model="user.id" autofill="autofill"/>发布于 2014-01-12 17:22:36
这里有一个解决方案,它比其他解决方案要简单得多,而且在语义上是合理的AngularJS:http://victorblog.com/2014/01/12/fixing-autocomplete-autofill-on-angularjs-form-submit/
myApp.directive('formAutofillFix', function() {
return function(scope, elem, attrs) {
// Fixes Chrome bug: https://groups.google.com/forum/#!topic/angular/6NlucSskQjY
elem.prop('method', 'POST');
// Fix autofill issues where Angular doesn't know about autofilled inputs
if(attrs.ngSubmit) {
setTimeout(function() {
elem.unbind('submit').submit(function(e) {
e.preventDefault();
elem.find('input, textarea, select').trigger('input').trigger('change').trigger('keydown');
scope.$apply(attrs.ngSubmit);
});
}, 0);
}
};
});然后,您只需将该指令附加到表单:
<form ng-submit="submitLoginForm()" form-autofill-fix>
<div>
<input type="email" ng-model="email" ng-required />
<input type="password" ng-model="password" ng-required />
<button type="submit">Log In</button>
</div>
</form>发布于 2013-05-29 04:33:28
脏代码,请检查问题https://github.com/angular/angular.js/issues/1460#issuecomment-18572604是否已修复,然后再使用此代码。这个指令在字段被填满时触发事件,而不仅仅是在提交之前(如果你必须在提交前处理输入)
.directive('autoFillableField', function() {
return {
restrict: "A",
require: "?ngModel",
link: function(scope, element, attrs, ngModel) {
setInterval(function() {
var prev_val = '';
if (!angular.isUndefined(attrs.xAutoFillPrevVal)) {
prev_val = attrs.xAutoFillPrevVal;
}
if (element.val()!=prev_val) {
if (!angular.isUndefined(ngModel)) {
if (!(element.val()=='' && ngModel.$pristine)) {
attrs.xAutoFillPrevVal = element.val();
scope.$apply(function() {
ngModel.$setViewValue(element.val());
});
}
}
else {
element.trigger('input');
element.trigger('change');
element.trigger('keyup');
attrs.xAutoFillPrevVal = element.val();
}
}
}, 300);
}
};
});https://stackoverflow.com/questions/14965968
复制相似问题