angular.js的双向绑定

angular.js的双向绑定就是可以将界面操作可以反映到数据,数据改变也可以体现在界面上。

界面到数据的传递,主要有UI事件,timeout超时器和ajax请求等回调操作。而数据到界面的传递则需要脏数据。只有前面界面到数据的操作发生的时候才会有脏数据检查。每次 UI 事件变更,ajax 还有 timeout 都会触发 $apply(),后者才会去调用$digest。

一.$watch对象

watch ={

name:name // 监听到的对象

getNewValue: function($scope){

}//获取到的新数据

listener:function(newValue,oldValue){

} //将新数据和旧数据进行比较,进行操作。

}

getNewValue() 可以得到当前$scope 上的最新值,listener 函数得到新值和旧值并进行一些操作。

1.创建$scope监听

function $scope(){

this.$$watchList= [];

}

$scope.propertype.$watch =  function(name,getNewValue,listener){

var  watch  ={

name:name,

getNewValue:getNewValue,

listener:listener || function(){}

}

this.$$watchList.push(watch);

}


$scope.prototype.$$digestOnce =function(){

var dirty;

var  list  =  this.$$watchList;

for(var i = 0; i < list.length; i++){

var newValue  =  list[i].getNewValue(this.value);

var oldValue  = list[i].last;

if(newValue !== oldValue){

list[i].listener(newValue,oldValue);

dirty =true;

}

list[i].last  = newValue;

return dirty;

}

}


$scope.prototype.$digest =function(){

var dirty=true;

var time=0;

if(dirty){

dirty  =  this.$$digestOnce();

time++;

if(time > 10 && dirty){

throw new error();

}

}

}

你可能感兴趣的:(angular.js的双向绑定)