[英]Angular - ng-change not firing when ng-model is changed
The input is the following: 输入如下:
<input type="text" ng-model="repair.test" ng-change="action()" />
The action()
is executed when I manually type and change the input. 当我手动输入和更改输入时执行
action()
。 However if I change the repair.test value by some other function programmatically, it doesnt fire the ng-change's action. 但是,如果我通过编程方式通过其他函数更改repair.test值,则不会触发ng-change的操作。 I have read the angular tutorial and it's probably the expected behavior.
我已阅读角度教程,这可能是预期的行为。
https://docs.angularjs.org/api/ng/directive/ngChange https://docs.angularjs.org/api/ng/directive/ngChange
"The expression is not evaluated when the value change is coming from the model." “当值变化来自模型时,不会评估表达式。” <- I need this too.
< - 我也需要这个。 How can I fire an action in controller, when the model changes in any way?
当模型以任何方式改变时,如何在控制器中触发动作? (typing in input or by any other function)
(输入输入或任何其他功能)
Thanks for the help. 谢谢您的帮助。
Edit: 编辑:
The model value is actually the form.$valid
, which has it's own Form controller around it (I think), that is why I used the action function to try to pass the value to the parent controller. 模型值实际上是
form.$valid
,它有自己的Form控制器(我认为),这就是我使用action函数尝试将值传递给父控制器的原因。 So $scope.$watch
at the moment doesn't work, only when it is initialised. 所以
$scope.$watch
目前不起作用,只有在初始化时。
The ngChange expression is only evaluated when a change in the input value causes a new value to be committed to the model. 仅当输入值的更改导致将新值提交给模型时,才会评估ngChange表达式。
It will not be evaluated: 它不会被评估:
$parsers
transformation pipeline has not changed $parsers
转换管道返回的值没有改变 Try to create a watcher using $scope.$watch - $watch(watchExpression, listener, [objectEquality]);
尝试使用$ scope创建一个观察者。$ watch -
$watch(watchExpression, listener, [objectEquality]);
Example 例
$scope.$watch('repair.test', function(newValue, oldValue) {
// ...
});
You can use a watcher-function in your controller 您可以在控制器中使用观察器功能
$scope.$watch('repair.test', function() {
$scope.action();
});
Another solution would be to use a directive that watched the model for any changes instead of using ng-change
. 另一种解决方案是使用一个指令来监视模型的任何变化,而不是使用
ng-change
。
app.directive('onModelChange', function($parse){
return {
restrict: "A",
require: "?ngModel",
link: function(scope, elem, attrs, ctrl) {
scope.$watch(attrs['ngModel'], function (newValue, oldValue) {
if (typeof(newValue) === "undefined" || newValue == oldValue) {
return;
}
var changeExpr = $parse(attrs['onModelChange']);
if (changeExpr) {
changeExpr(scope);
}
});
}
};
});
Then you would use it like so: 然后你会像这样使用它:
<input class="value" type="text" ng-model="myVar" on-model-change="doSomething(myVar)"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.