问题描述
假如我想做一些像自动运行一些code(如将数据保存到服务器),只要一个模型的值的变化。通过设置类似 NG-变化
对那些可能改变模型中的每个控制做到这一点的唯一途径?
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?
也就是说,与意见,正确的事情的模型,而无需显式连接什么东西改变了改变。是否有一个模拟能够运行code,它保存到服务器?类似
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-模型,角正在建立 $表()
ES为你在幕后。
In views with {{}}
and/or ng-model, Angular is setting up $watch()
es for you behind the scenes.
在默认情况下<$c$c>$watch$c$c>参照进行比较。如果将第三个参数 $观看
到真正
,角将改为浅监视更改的对象。对于数组,这意味着比较数组的项目,对象映射,这意味着看属性。因此,这应该做你想要什么:
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);
更新:角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:自动侦测模式的变革的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!