![](/img/trans.png)
[英]Angular $scope.$watch - creating an array and total depending on ng-model/length
[英]$scope.$watch is not triggered when ng-model is undefined?
问题:
我试图在具有严格属性(例如max
, min
, maxlength
和step
的数字输入中使用的ng模型上使用$scope.$watch
方法。
当输入中插入的值超过这些属性中的任何一个时,ng-model检索undefined
。
因此,最终发生的事情是:每次我们更改输入值时,都会触发$scope.$watch
。 一旦值未定义,则只有在插入的值再次有效时(换句话说,遵循属性规则(最大,最小,最大长度和步长)),才会再次触发该值。
例如
用户输入: -2,4-> $scope.$watch
被触发,并输出newValue
为undefined
。
用户添加一个新数字: -2,44-> $scope.$watch
不再触发,这种方式。
main.js
$scope.$watch("user.input.base.sphere", function(newValue, oldValue) {
console.log(newValue);
}
** index.html
<input
ng-cloak
type="number"
ng-class="user.settings.input.sphere.class"
autocomplete="off"
required
name="sphere"
id="in-sphere"
title="Sphere"
step="{{user.filter.sphere.step}}"
min="{{user.filter.sphere.min}}"
max="{{user.filter.sphere.max}}"
maxlength="{{user.filter.sphere.maxlength}}"
placeholder="{{user.filter.sphere.placeholder}}"
ng-model="user.input.base.sphere"
select-on-click
sphere>
问题:即使在未定义的ng-model
我如何仍可以让$scope.$watch
触发
您可以将以下功能附加到ng-keyup
指令。 该函数将获取对表单控件的引用,并读取用户键入的值,即使模型中的值尚未更新。
$scope.changeHandler = function (a) {
var element = angular.element(document.querySelector('#in-sphere'))[0];
console.log(element.value);
}
将此附加到您的表单控件: ng-keyup='changeHandler()'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.