浅谈angular.js中实现双向绑定的方法$watch $digest $apply
Angular.js中的特性,双向绑定.
多么神奇的功能,让视图的改变直接反应到数据中,数据的改变又实时的通知到视图,如何做到的?
这要归功于scope下面3个重要的方法:
$watch
$digest
$apply
他们的区别是什么,我们来介绍下:
$watch
这是一个监听scope上数据的监听器
方法说明:
$scope.$watch('参数',function(newValue,oldValue){ //逻辑处理 })
上面我们就是创建了一个监听器.
‘参数'就是$scope对象下的一个对象(或者一个对象的属性),注意,这里是字符串形式.
假如你要监听$scope.name属性.
$scope.$watch('name',function(newValue,oldValue){ //逻辑处理 })
如上代码,‘name'需要引号
参数后面跟着回调函数,回调函数参数返回了被监听属性,变化后的新值,以前变化前的旧值.
$digest
他负责检查scope中的数据是否发生了变化,如果某个属性有变化,马上会通知此属性的监听器($watch注册的监听器),触发监听器,执行回调函数.
$apply
这个方法和$digest很相似,$digest检查scope中的所有数据
$apply相当于检查rootScope中的所有数据,他会从父级到子级来检查所有数据
$apply()==$rootScope.$digest()
$apply()方法有两种形式.
第一种接受一个function作为参数.
这样触发$digest函数并且执行一次参数中的function
第二种 不接受任何参数.
这样只是触发一轮$digest父级到子级的循环
Angular.js中一班不会直接调用$digest,而是用$scope.$apply()来代替
我没有设定监视器,为什么视图和数据可以双向绑定
比如一个文本框ng-model="name"
这时其实$scope对象下已经有了一个属性name来对应和上面的视图进行双向绑定
如何实现的?
其实,当我们定义ng-model="name" 或者ng-bind="name"或者{{name}}
这时angular.js会在$scope模型上自动为“name”属性设置一个监听器:
$scope.$watch('name',function(newValue,oldValue){ //监听name属性的变化 });
原来这里angular.js帮我们自动创建了一个监听器,所以此属性和$scope.name数据才会实时的双向绑定.
当然,有时候你也会发现明明数据变化了.但是UI没有刷新,是双向绑定失效了吗?
没有
只是在$scope模型遍历digest循环时,你的数据还没有返回来,
比如异步调用方法,callbac返回的数据
比如你在setTimeout设置了定时触发函数,然后修改模型数据
总之,是错过了$scope模型的digest循环,导致模型没有通知UI去根据新数据刷新.
遇到这样的问题怎么办?
我们只好自己去手动调用digest来循环检查一次数据.实现双向绑定
上面我们已经说过,通常不要去直接调用digest方法,而是手动调用$apply方法,间接实现触发$digest循环.
如下:
setTimeout(function(){ $scope.name='一介布衣'; $scope.$apply(); },2000);
问题来了,上面时候该去手动调用apply方法
目前为止,angular.js为一部分指令和服务自动实现了$apply()方法.
例如,ng-click,ng-model,$timeout服务,$http服务等
调用后,angular.js会自动帮我们调用$apply()来实现数据双向绑定.