第一部分:$watch

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

$watch(watchExpression, listener, objectEquality);

每个参数的说明如下:

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

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

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

可参考:

http://yuankeqiang.lofter.com/post/8de51_1454f93

http://www.angularjs.cn/A0a6

官网:http://docs.angularjs.cn/api/ng/type/$rootScope.Scope

第二部分:$watch,$digest和$apply

最近项目上使用了比较多的angular JS,一直都对它感觉比较陌生,总觉得有点反直觉,这段时间,准备下定决心弄明白,这个框架到底是怎么一回事,以及它的工作原理,生命周期……一点一点的啃完它吧。首先,让我们先来看看watch、digest、$apply这三个方法吧!

  • $watch(watchExpression, listener, objectEquality) 
Param Type Details
watchExpression

function()

string

Expression that is evaluated on each $digest cycle. A change in the return value triggers a call to the listener.

  • string: Evaluated as expression
  • function(scope): called with current scope as a parameter.
listener
(optional)

function()

string

Callback called whenever the return value of the watchExpressionchanges.

  • string: Evaluated as expression
  • function(newValue, oldValue, scope): called with current and previous values as parameters.
objectEquality
(optional)
boolean Compare object for equality rather than for reference. 

从表格中可以看到,watchExpression和listener可以是一个string,也可以是一个function(scope)。该表达式在每次调用了$digest方法之后都会重新算值,如果返回值发生了改变,listener就会执行。在判断newValue和oldValue是否相等时,会递归的调用angular.equals方法。在保存值以备后用的时候调用的是angular.copy方法。listener在执行的时候,可能会修改数据从而触发其他的listener或者自己直到没有检测到改变为止。Rerun Iteration的上限是10次,这样能够保证不会出现死循环的情况。
     $watch的基本结构如下:

//$scope.$watch(<function/expression>, <handler>);
$scope.$watch('foo', function(newVal, oldVal) {
console.log(newVal, oldVal);
});
//or
$scope.$watch(function() {
return $scope.foo;
}, function(newVal, oldVal) {
console.log(newVal, oldVal);
});
  • $digest()

该方法会触发当前scope以及child scope中的所有watchers,因为watcher的listener可能会改变model,所以$digest方法会一直触发watchers直到不再有listener被触发。当然这也有可能会导致死循环,不过angular也帮我们设置了上限10!否则会抛出“Maximum iteration limit exceeded.”。
     通常,我们不在controller或者directive中直接调用digest方法,而是调apply方法,让apply方法去调用digest方法。
     如何调用该方法呢?

$scope.$digest();
  • $apply(exp)
Param Type Details
exp
(optional)

string

function()

An angular expression to be executed.

  • string: execute using the rules as defined in expression.
  • function(scope): execute the function with current scope parameter.

个人理解,apply方法就是将digest方法包装了一层,exp是可选参数,可以是一个string,也可以是function(scope)。伪代码(来自官方文档)如下:

function $apply(expr) {
try {
return$eval(expr);
} catch(e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}

$apply方法使得我们可以在angular里面执行angular框架之外的表达式,比如说:浏览器DOM事件、setTimeout、XHR或其他第三方的库。由于我们要在angular框架内调用,我们必须得准备相应的scope。调用方式如下:

$scope.$apply('foo = "test"');
//or
$scope.$apply(function(scope) {
scope.foo = 'test';
});
//or
$scope.$apply(function(){
$scope.foo = 'test';
});
  • watch、digest、$apply是如何与视图的更新相关联的呢?
  1. directive给scope上的一个model注册watch来监视它的变化,listener会去更新DOM元素的值。
  2. directive给DOM中的一些元素注册event handler,它们会取得DOM中元素的值,然后更新到scope上的model中去。它也会触发apply或者$digest。
  3. 当你通过框架更新了scope上model的值,比如说:http.get(),当它完成后也会触发$digest方法。
  4. digest会去检查directive注册的watch,发现值被修改就会触发相关联的handler,然后更新DOM元素。

至于angular js为什么要这么做,请看我上一篇博客angular js之scope.$apply方法

  • $watch
  1. 当scope上的值发生变化时,尽量在directive中使用watch去更新DOM。
  2. 尽量不要再controller中使用$watch方法,它会增加测试的复杂度,而且也不必要。可以使用scope上的方法去更新被改变的值。
  • digest、apply
  1. 在directive中使用digest/apply使angular知道一个异步请求完成后的变化,比如说DOM Event。
  2. 在service中使用digest/apply使angular知道一个异步操作已经完成,比如说WebSocket、或者第三方的库。
  3. 尽量不要再controller中使用digest/apply,这样的话测试起来会比较困难。

===============================================================================

  • 关于angular.equals方法

该方法支持value types,regular expressions、arrays、objects。官方文档写的很清楚:
Two objects or values are considered equivalent if at least one of the following is true:

  1. Both objects or values pass === comparison.
  2. Both objects or values are of the same type and all of their properties are equal by comparing them with angular.equals.
  3. Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  4. Both values represent the same regular expression (In JavasScript, /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual representation matches).

During a property comparison, properties of function type and properties with names that begin with $ are ignored.
Scope and DOM Window objects are being compared only by identify (===).

来源:http://www.cnblogs.com/penghongwei/p/3400535.html

最新文章

  1. CSharpGL - Object Oriented OpenGL in C#
  2. Linux常用目录及文件
  3. 《Administrator&#39;s Guide》之Managing Memory
  4. EasyDarwin
  5. 浮动框控制及切换、banner随机数js
  6. redis 内存
  7. Win10/UWP开发—使用Cortana语音指令启动前台App
  8. json 增删改 加 排序
  9. shell 实例收集
  10. MapReduce优化
  11. C语言--基本运算符
  12. php实现json
  13. HDU 3487 Play with Chain | Splay
  14. PPTP-VPN日志功能,记录用户登录时间,流量统计,IP地址等信息
  15. python基础知识巩固(os.walk)
  16. ElasticSearch日常使用脚本
  17. 背水一战 Windows 10 (115) - 后台任务: 通过 toast 激活后台任务, 定时激活后台任务
  18. cat查阅文件技巧
  19. [NOI 2017]整数
  20. 洛谷 P1282 多米诺骨牌(&quot;01&quot;背包)

热门文章

  1. Vosio秘钥
  2. Qt+数据库
  3. HDU 1166 敌兵布阵 【线段树-点修改--计算区间和】
  4. CentOS 7防火墙设置开放80端口
  5. Linux基本常用命令
  6. php flock 使用实例
  7. java基础(2)-面向对象(2)
  8. R语言笔记006——分组获取描述性统计量
  9. Ubuntu下用crontab 部署定时任务
  10. CEF3.2623使用记录:windows编译