AngularJS:自动检测模型的变化 [英] AngularJS : automatically detect change in model
问题描述
假设我想在模型的值发生变化时自动运行一些代码(例如将数据保存到服务器).通过在每个可能改变模型的控件上设置诸如 ng-change
之类的东西来做到这一点是唯一的方法吗?
Suppose I wanted to do something like automatically run some code (like saving data to a server) whenever a model's values change. Is the only way to do this by setting something like ng-change
on each control that could possibly alter the model?
也就是说,有了视图,事情会随着模型的改变而改变,而不必显式地连接任何东西.是否可以运行保存到服务器的代码?类似的东西
Ie, with views, things change right as the model is changed without having to explicitly hook anything up. Is there an analog to being able to run code that saves to a server? Something like
myModel.on('change', function() {
$.post("/my-url", ...);
});
就像你看到的骨干之类的东西.
like you might see with something like backbone.
推荐答案
在带有 {{}}
和/或 ng-model 的视图中,Angular 正在设置 $watch()
es 在幕后为您服务.
In views with {{}}
and/or ng-model, Angular is setting up $watch()
es for you behind the scenes.
默认情况下 $watch
通过引用进行比较.如果您将第三个参数 $watch
设置为 true
,Angular 将改为浅"观察对象的变化.对于数组,这意味着比较数组项,对于对象映射,这意味着查看属性.所以这应该做你想做的:
By default $watch
compares by reference. If you set the third parameter to $watch
to true
, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:
$scope.$watch('myModel', function() { ... }, true);
更新:Angular v1.2 为此添加了一个新方法,`$watchCollection():
Update: Angular v1.2 added a new method for this, `$watchCollection():
$scope.$watchCollection('myModel', function() { ... });
请注意,浅"一词用于描述比较而不是深",因为没有遵循引用——例如,如果被监视的对象包含一个引用另一个对象的属性值,则该引用不是接着比较另一个对象.
Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.
这篇关于AngularJS:自动检测模型的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!