我有一个基本上监视元素值的指令。
此元素的 ng-maxlength
属性设置为 150。当我传递 150 个字符时,$watch
不再触发。此外,当我使用 ctrl + x 删除整个文本时,$watch
再次不会被触发。
输入元素
<input type="text" ng-model="company.fullName" name="companyFullName" required ng-maxlength="150" ng-input-validate />
指令
enlabApp.directive('ngInputValidate', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
scope.$watch(function () { return ctrl.$modelValue; }, function (value) {
console.log('test');
});
}
};
});
当我删除 ng-maxlength
指令时,问题就消失了。
最佳答案
您正在使用ng-maxlength=150
,这意味着 Angular 将对字符数执行验证,并相应地更新$modelValue
。这意味着当它无效时(如果长度超过)$modelValue
将是undefined
,然后您通过执行ctl-x
删除该值,然后消化循环运行,模型值再次变为未定义
,因为不存在任何值,并且与之前的值没有区别,并且观察器不会触发(仅当modelValue
时观察器才会触发> 变脏)。
所以使用 $viewValue
或 element[0].value
(我不建议)。这样做:-
scope.$watch(function () {
return ctrl.$viewValue;
}, function (value) {
console.log('Triggered');
});
- $viewValue: View 中的实际字符串值。
- $modelValue:模型中与控件绑定(bind)的值。
请记住,如果您想限制 minlength
属性,使用 ng-minlength
仅用于验证,它不会限制用户输入/粘贴更多字符这是要走的路
另请注意,您不必在 ngModel
上注册 watch ,您可以使用 $viewChangeListeners
也无需创建额外的 watch 。
Array of functions to execute whenever the view value has changed. It is called with no arguments, and its return value is ignored. This can be used in place of additional $watches against the model value.
ctrl.$viewChangeListeners.push(function(){//... });
关于javascript - 使用 ng-maxlength 时不会触发 $watch 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25431442/