$watch 与 ng-change、ng-checked 等的角度触发器变化 [英] angular trigger changes with $watch vs ng-change, ng-checked, etc
问题描述
目前我们可以通过多种方式监控数据变化.我们可以使用 $watch
触发模型更改,我们可以向元素添加指令并将一些操作绑定到它.
Currently we could monitor data changes with several ways. We could trigger model changes with $watch
and we could add directives to elements and bind some actions to it.
在很多情况下有点令人困惑,所以我很好奇,每个变体的利弊,我们应该何时使用 $watch
绑定,以及何时使用像 ng 这样的指令-更改
?
It's a little bit confusing in many cases, so I'm curious, which is pro and cons of each variant and when should we use $watch
binding, and when directives like ng-change
?
推荐答案
$watch
和 ngChange
的用法完全不同:
Both $watch
and ngChange
have totally different usages:
假设您在范围上定义了一个模型:
Lets say you have a model defined on a scope:
$scope.myModel = [
{
"foo":"bar"
}
];
现在,如果您想在 myModel
发生任何更改时执行某些操作,您可以使用 $watch
:
Now if you want to do something whenever any changes happen to myModel
you would use $watch
:
$scope.$watch("myModel", function(newValue, oldValue){
// do something
});
ngChange
是一个指令,它会在用户更改输入时评估给定的表达式:
ngChange
is a directive that would evaluate given expression when user changes the input:
<select ng-model="selectedOption" ng-options="option for option in options"
ng-change="myModel=selectedOption"></select>
简而言之,您通常会将 ngChange
绑定到某个 HTML 元素.$watch
用于模型.
In short, you would normally bind ngChange
to some HTML element. While $watch
is for the models.
这篇关于$watch 与 ng-change、ng-checked 等的角度触发器变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!