AngularJS的双向绑定是如何实现的?

匿名网友 匿名网友 发布于: 2015-12-21 00:00:00
阅读 108 收藏 0 点赞 0 评论 0

AngularJS在$scope变量中使用脏值检查来实现了数据双向绑定,当事件发生时会调用scope中的所有watch方法进行脏值检查

  • $watch:$scope提供$watch方法来监听数据对象的改变。ng-model等指令会自动创建一个$watch,以保证对数据对象属性的监听。这些$watch会形成一个列表,等待通知执行。
  • $apply:$scope提供$apply方法传播数据对象的改变。不在angularjs执行上下文中对数据模型进行赋值的时候(例如在setTimeout方法中赋值),将无法监听到数据模型的变化,这时候就需要$apply方法将数据变化语句包裹起来:

setTimeout(function(){

$scope.$apply(function(){

$scope.attr=’change’;

});

},1000);

这时候,数据模型改变的时候将会触发对应的$watch。在$apply执行后会触发一个$scope.$digest(),这个方法会依次检查被监听的属性,发现数据改变的时候会调用$watch中的回调。

myModule.directive(‘namespaceDirectiveName’, function factory(injectables) {

var directiveDefinitionObject = {

restrict: string,//指令的使用方式,包括标签,属性,类,注释

priority: number,//指令执行的优先级

template: string,//指令使用的模板,用HTML字符串的形式表示

templateUrl: string,//从指定的url地址加载模板

replace: bool,//是否用模板替换当前元素,若为false,则append在当前元素上

transclude: bool,//是否将当前元素的内容转移到模板中

scope: bool or object,//指定指令的作用域

require:”^$http”

//定义与其他指令进行交互的接口函数

controller: function controllerConstructor($scope, $element, $attrs, $transclude,$http){…},

require: string,//指定需要依赖的其他指令

link: function postLink(scope, iElement, iAttrs) {…},//以编程的方式操作DOM,包括添加监听器等

compile: function compile(tElement, tAttrs, transclude){

return: {

pre: function preLink(scope, iElement, iAttrs, controller){…},

post: function postLink(scope, iElement, iAttrs, controller){…}

}

}//编程的方式修改DOM模板的副本,可以返回链接函数

};

return directiveDefinitionObject;

});

评论列表
文章目录