官方文档

$watch简单使用

$watch是一个scope函数,用于监听模型变化,当你的模型部分发生变化时它会通知你。

$watch(watchExpression, listener, objectEquality);

每个参数的说明如下:

watchExpression:监听的对象,它可以是一个angular表达式如'name',或函数如function(){return $scope.name}。

listener: 当watchExpression变化时会被调用的函数或者表达式,它接收3个参数:newValue(新值), oldValue(旧值), scope(作用域的引用)

objectEquality:是否深度监听,如果设置为true,它告诉Angular检查所监控的对象中每一个属性的变化. 如果你希望监控数组的个别元素或者对象的属性而不是一个普通的值, 那么你应该使用它

举个例子:

$scope.name = 'hello';

var watch = $scope.$watch('name',function(newValue,oldValue, scope){
console.log(newValue + ' - ' + oldValue);
}); //1秒后改变name变量的值 $timeout(function(){
  $scope.name = "world";
},1000);

如何注销$watch

太多的$watch将会导致性能问题,$watch如果不再使用,我们最好将其释放掉。

$watch函数返回一个注销监听的函数,如果我们想监控一个属性,然后在稍后注销它,可以使用下面的方式:

    var counter = 0;
var watch = $scope.$watch('name',function(newValue,oldValue, scope){
console.log('new:' + newValue + ' old:' + oldValue);
counter ++;
//超出停止注销watch
if (counter > 5 ) {
watch();
}
});

$watchGroup(watchExpressions, listener);

watchExpressions是数组类型

如果要监听多个变量就要写很多个watch,这显然不是很好的作用。

使用$watchGroup可同时监听多个变量,如果任一一个变量发生变化就会触发listener。

$scope.teamScore = 0;
$scope.time = 0;
$scope.$watchGroup(['teamScore', 'time'], function(newVal, oldVal) {
if(newVal[0] > 20){
$scope.matchStatus = 'win';
}
else if (newVal[1] > 60){
$scope.matchStatus = 'times up';
});

$watchCollection(obj, listener);

Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties). If a change is detected, the listener callback is fired.

针对对象属性的浅层监视(Shallow Watch),当属性发生变化时触发(对于数组,指的是监视数组的元素;对于字典对象,指的是监视其属性) 触发listener的回调操作。

其实完全可以使用$watch,这里是对性能的考虑。

关于这三个方法的 在线例子

另外注意的是这三个方法貌似是1.3版本之后才加入的。

stackoverflow上有人做了对比,我测试了几个是正确的。

$watch() will be triggered by:

$scope.myArray = [];
$scope.myArray = null;
$scope.myArray = someOtherArray;

$watchCollection() will be triggered by everything above AND:

$scope.myArray.push({}); // add element
$scope.myArray.splice(0, 1); // remove element
$scope.myArray[0] = {}; // assign index to different value

$watch(..., true) will be triggered by EVERYTHING above AND:

$scope.myArray[0].someProperty = "someValue";

JUST ONE MORE THING...

$watch() is the only one that fires when an array is replaced with another with the same exact content. For example:

$scope.myArray = ["Apples", "Bananas", "Orange" ];

var newArray = [];
newArray.push("Apples");
newArray.push("Bananas");
newArray.push("Orange"); $scope.myArray = newArray;

Below is a link to an example JSFiddle that uses all the different watch combinations and outputs log messages to indicate which "watches" were triggered:

http://jsfiddle.net/luisperezphd/2zj9k872/

个人总结:

1. $watchGroup 的第一个参数要传数组,$watchCollection的第一个参数要传对象

2. 监视对象和数组而且监视层次不是特别深,优先使用$watchCollection, $watchCollection可以方便的监视数组的插入,移除。

3. 要同时监视多个变量并执行同一逻辑使用$watchGroup

4. 除此一般情况下使用$watch,如果你知道数据结构的深度,可以直接这样监视。 当第三个参数true,表示深度监测,如果watch的变量比较复杂,效率会变低。

$watch('user.data', (newVal, oldVal) => {
  if(newVal !== oldVal) { }
})

参考:

http://stackoverflow.com/questions/26535415/angularjs-watch-vs-watchcollection-which-is-better-for-performance

http://blog.csdn.net/dm_vincent/article/details/51620193

http://blog.csdn.net/u010451286/article/details/50635839

随机推荐

  1. LintCode,hihoCoder,LeetCode有什么区别?

    https://www.zhihu.com/question/31218682 知乎用户 9 人赞同了该回答 LintCode 和LeetCode的题差不太多LintCode 有中文,不过没有用户讨论 ...

  2. Linux tree命令详解

    tree: 查看目录结构 tree常见命令参数 usage: tree [-adfghilnpqrstuvxACDFNS] [-H baseHREF] [-T title ] [-L level [- ...

  3. KInect AR沙盒制作的一点小经验

    最近在微博上看到这样一条 微博  >点这看< 看起来非常有意思,就去Google了一下如何制作. 没想到这是一个开源项目,而且还告诉你如何安装 OK,接下来就说说我的制作过程. 首先,先放 ...

  4. php算法基础----时间复杂度和空间复杂度

    算法复杂度分为时间复杂度和空间复杂度. 其作用: 时间复杂度是指执行算法所需要的计算工作量: 而空间复杂度是指执行这个算法所需要的内存空间. (算法的复杂性体现在运行该算法时的计算机所需资源的多少上, ...

  5. 用一个变量表示 ----------"序号,名称,价格"

     goods = [{"name": "电脑", "price": 1999},          {"name": & ...

  6. 导出类成员里含有stl对象

    How to export an instantiation of a Standard Template Library (STL) class and a class that contains ...

  7. DevExpress01、独立使用的控件

    XtraEditors 库提供了只能独立使用的控件,也就是说不能在容器控件的内置编辑中使用它们. 这些控件包括: 几种类型的列表框.数据导航控件.滚动条和一个按钮控件. 这些控件都是 BaseStyl ...

  8. Istio 1.1尝鲜记

    近几天Istio1.1的发布引起了技术界巨大的反响,为了让更多技术爱好者能够亲自体验Istio1.1,公司的技术大佬赶出了这篇尝鲜教程,其中包括环境.安装.可能遇到的问题及解决方式等,希望对大家有所帮 ...

  9. [转]Linux下查看CPU信息、机器型号等硬件信息

    From: http://www.jbxue.com/LINUXjishu/14582.html 查看CPU信息(型号) : # cat /proc/cpuinfo | grep name | cut ...

  10. JavaScript实现限时抢购实例

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...