问题描述
目前,我们可以监督几个方面的数据变化。我们可能会引发与 $模式的变化看
键,我们可以添加指令,以元素并结合了一些行动吧。
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.
这是在很多情况下,稍微有点混乱,所以我很好奇,这是亲和每个变量的利弊,我们何时应该使用 $观看
绑定,当指令就像 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
?
推荐答案
两个 $观看
和 ngChange
有完全不同的用途:
Both $watch
and ngChange
have totally different usages:
假设你有一个范围内定义的模型:
Lets say you have a model defined on a scope:
$scope.myModel = [
{
"foo":"bar"
}
];
:如果你想要做的,只要任何变化发生在基于myModel
你可以使用 $观看
的东西
现在p>
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
是将评估给出前pression指令,当用户改变输入:
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元素。而 $观看
是模型。
In short, you would normally bind ngChange
to some HTML element. While $watch
is for the models.
这篇关于以$手表VS NG-变化,NG-检查等角度触发的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!