gpt4 book ai didi

javascript - 使用 ng-maxlength 时不会触发 $watch 监听器

转载 作者:行者123 更新时间:2023-11-29 18:13:14 25 4
gpt4 key购买 nike

我有一个基本上监视元素值的指令。

此元素具有设置为 150 的 ng-maxlength 属性。当我传递 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 删除值然后 digest循环运行并且模型值再次变为 undefined 因为没有值存在并且与先前的值没有区别并且观察者不会触发(只有当 modelValue 变脏了)。

因此请使用 $viewValueelement[0].value(我不建议这样做)。也一样:-

        scope.$watch(function () { 
return ctrl.$viewValue;
}, function (value) {
console.log('Triggered');
});
  • $viewValue: View 中的实际字符串值。
  • $modelValue:控件绑定(bind)到的模型中的值。

请记住,使用 ng-minlength 仅用于验证,如果您想限制 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com