双向绑定的三个重要方法:

  • $scope.$apply()
  • $scope.$digest()
  • $scope.$watch()

一、$scope.$watch()

  我理解的$watch就是将对某个数据的监听器对象存储在$scope下。当给$watch指定如下两个函数,就可以创建一个监听器:

  • 一个监控函数,我们通常传进去的是一个表达式,比如说“user.firstName”,但框架本身实际上是调用了一个函数,返回指定所关注的那部分数据。
  • 一个监听函数,用于在数据变更的时候接受提示。

  为了实现$watch,我们需要存储监听器对象。在Scope构造函数上添加一个数组:

function Scope() {
this.$$watchers = [];
}

$$在angular中表示这个变量被当作私有的来考虑,不应当在外部代码中调用。

  现在我们正式定义$watch()方法,源代码如下所示:

$watch: function(watchExp, listener, objectEquality) {
var scope = this,
get = compileToFn(watchExp, 'watch'),
array = scope.$$watchers,
watcher = {
fn: listener,
last: initWatchVal,
get: get,
exp: watchExp,
eq: !!objectEquality
}; // in the case user pass string, we need to compile it, do we really need this ?
if (!isFunction(listener)) {
var listenFn = compileToFn(listener || noop, 'listener');
watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
} if (typeof watchExp == 'string' && get.constant) {
var originalFn = watcher.fn;
watcher.fn = function(newVal, oldVal, scope) {
originalFn.call(this, newVal, oldVal, scope);
arrayRemove(array, watcher);
};
} if (!array) {
array = scope.$$watchers = [];
}
// we use unshift since we use a while loop in $digest for speed.
// the while loop reads in reverse order.
array.unshift(watcher); return function() {
arrayRemove(array, watcher);
};
},

其中$$watchers就是wo我们上述的scope中存储监听器的数组,$watch()通过unshift()方法将监听器对象加入数组。

二、$scope.$digest()

$digest函数的作用是简而言之就是作用域上遍历所有监听器,也就是$scope.$$watchers,调用每个监听器对象下的监控函数,并且比较它返回的值和上一次返回值的差异。如果不相同,监听器就是脏的,它的监听函数就应当被调用。源代码如下所示:

$digest: function() {
var watch, value, last,
watchers,
asyncQueue = this.$$asyncQueue,
postDigestQueue = this.$$postDigestQueue,
length,
dirty, ttl = TTL,
next, current, target = this,
watchLog = [],
logIdx, logMsg, asyncTask; beginPhase('$digest'); do { // "while dirty" loop
dirty = false;
current = target; while(asyncQueue.length) {
try {
asyncTask = asyncQueue.shift();
asyncTask.scope.$eval(asyncTask.expression);
} catch (e) {
$exceptionHandler(e);
}
} do { // "traverse the scopes" loop
if ((watchers = current.$$watchers)) {
// process our watches
length = watchers.length;
while (length--) {
try {
watch = watchers[length];
// Most common watches are on primitives, in which case we can short
// circuit it with === operator, only when === fails do we use .equals
if (watch && (value = watch.get(current)) !== (last = watch.last) &&
!(watch.eq
? equals(value, last)
: (typeof value == 'number' && typeof last == 'number'
&& isNaN(value) && isNaN(last)))) {
dirty = true;
watch.last = watch.eq ? copy(value) : value;
watch.fn(value, ((last === initWatchVal) ? value : last), current);
if (ttl < 5) {
logIdx = 4 - ttl;
if (!watchLog[logIdx]) watchLog[logIdx] = [];
logMsg = (isFunction(watch.exp))
? 'fn: ' + (watch.exp.name || watch.exp.toString())
: watch.exp;
logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
watchLog[logIdx].push(logMsg);
}
}
} catch (e) {
$exceptionHandler(e);
}
}
} // Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $broadcast
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next)); if(dirty && !(ttl--)) {
clearPhase();
throw $rootScopeMinErr('infdig',
'{0} $digest() iterations reached. Aborting!\nWatchers fired in the last 5 iterations: {1}',
TTL, toJson(watchLog));
}
} while (dirty || asyncQueue.length); clearPhase(); while(postDigestQueue.length) {
try {
postDigestQueue.shift()();
} catch (e) {
$exceptionHandler(e);
}
}
},

三、$scope.$apply()

  $apply使用函数作参数,它用$eval执行这个函数,然后通过$digest触发digest循环。源代码如下所示:

$apply: function(expr) {
try {
beginPhase('$apply');
return this.$eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
clearPhase();
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
},

  可以看到,在apply方法里其实是调用了digest方法的,那么为什么要多增加一个apply来调用digest呢,可以看到这段代码中并没有直接调用digest而是首先进行了对expr的检验,也就是eval方法,这个方法如果校验不通过,是会抛出异常的,而angular并不推荐外部直接调用digest,所以就增加了apply方法来间接调用。

  利用$apply(),我们可以执行一些与Angular无关的代码,这些代码也还是可以改变作用域上的东西,$apply可以保证作用域上的监听器可以检测这些变更。

四、何时执行和跳出digest loop呢?

  引用网上一张图来解释

资料引用自:http://my.oschina.net/brant/blog/419641

AngularJs双向绑定详解的更多相关文章

  1. AngularJS模块的详解

    AngularJS模块的详解 在讲angularjs的模块之前,我们先介绍一下angular的一些知识点: AngularJS是纯客户端技术,完全用Javascript编写的.它使用的是网页开发的常规 ...

  2. AngularJS开发指南6:AngularJS表单详解

    表单控件(input, select, textarea )是用来获取用户输入的.表单则是一组有联系的表单控件的集合. 用户能通过表单和表单控件提供验证的服务,知道自己的输入是否合法.这样能让用户交互 ...

  3. Angularjs 双向绑定机制解析

    文章转自:http://www.2cto.com/kf/201408/327594.html AngularJs 的元素与模型双向绑定依赖于循环检测它们之间的值,这种做法叫做脏检测,这几天研究了一下其 ...

  4. AngularJs自定义指令详解(5) - link

    在指令中操作DOM,我们需要link参数,这参数要求声明一个函数,称之为链接函数. 写法: link: function(scope, element, attrs) { // 在这里操作DOM} 如 ...

  5. AngularJS指令的详解

    指令作为AngularJS中最为重要的部分,所以这个框架本身也是自带了比较多的的指令,但是在开发中,这些指令通常不能满足我们的需要,所以我们也是需要自定义一些指令的.指令是我们用来扩展浏览器能力的技术 ...

  6. AngularJs自定义指令详解(3) - scope

    我们之所以要定义指令,目的是重用指令.假设有这么一个应用场景:在同一个html里使用了两次my-directive,第一个my-directive要展示的是Hello World,第二个my-dire ...

  7. AngularJS开发指南14:AngularJS的服务详解

    服务是一种由服务器端带到客户端的特性,它由来已久.AngularJS应用中的服务是一些用依赖注入捆绑在一起的可替换的对象.服务是最常和依赖注入一起用的,它也是AngularJS中的关键特性. 接下来, ...

  8. angularjs directive 实例 详解

    前面提到了angularjs的factory,service,provider,这个可以理解成php的model,这种model是不带html的,今天所说的directive,也可以理解成php的mo ...

  9. angularjs的directive详解

    Directive(指令)笔者认为是AngularJ非常强大而有有用的功能之一.它就相当于为我们写了公共的自定义DOM元素或CLASS属性或ATTR属性,并且它不只是单单如此,你还可以在它的基础上来操 ...

随机推荐

  1. pointcloud(点云)与mesh(面元)模型的区别

    点元与面元

  2. [转]How to Clean the Global Assembly Cache

    本文转自:https://www.techwalla.com/articles/how-to-clean-the-global-assembly-cache The Global Assembly C ...

  3. svn cleanup失败解决方法

    一般网上给出的解决方法是使用sqlite清空.svn\wc.db的工作队列表(work_queue) 后来发现都打不开wc.db 百度一下: 保留当前目录源码,删除 .svn(隐藏)文件夹,重新che ...

  4. Android-FileIOUtils工具类

    文件读写相关工具类 public final class FileIOUtils { private FileIOUtils() { throw new UnsupportedOperationExc ...

  5. 自我介绍和Github的初次体验

    姓名:袁宇鹏    学号:1413042045    班级:网络工程142    兴趣爱好:篮球,看书 写过的代码:用C++写过,只能算是看看这源程序修改. 没有开发过任何程序 Github使用流程: ...

  6. java 传参数时 类型后跟 3个点 "..." 的意义

    对照代码和运行结果便知"..." 的意义 import java.util.ArrayList; public class StringDemo { public static v ...

  7. java数据结构和算法03(队列和优先级队列)

    什么是队列呢?其实队列跟栈很像,我们可以把栈的底部给弄开,这样数据就可以从下面漏出来了,我们就从下面拿就好了. 可以看到队列是新进先出,就跟我们显示生活中的排队一样,买火车票,飞机票等一样,先去的肯定 ...

  8. Spring Boot 学习系列(06)—采用log4j2记录日志

    此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 为什么选择log4j2 log4j2相比于log4j1.x和logback来说,具有更快的执行速度.同时也支 ...

  9. Linux程序设计:目录维护

    一.相关系统调用 1.1 chmod 改变访问权限. #include <sys/stat.h> int chmod(const char *path, mode_t mode) 1.2 ...

  10. python网络编程--进程(方法和通信),锁, 队列,生产者消费者模型

    1.进程 正在进行的一个过程或者说一个任务.负责执行任务的是cpu 进程(Process: 是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础.在 ...