angular.js的雙向綁定就是可以將界面操作可以反映到數(shù)據(jù),數(shù)據(jù)改變也可以體現(xiàn)在界面上。
界面到數(shù)據(jù)的傳遞,主要有UI事件,timeout超時器和ajax請求等回調(diào)操作。而數(shù)據(jù)到界面的傳遞則需要臟數(shù)據(jù)。只有前面界面到數(shù)據(jù)的操作發(fā)生的時候才會有臟數(shù)據(jù)檢查。每次 UI 事件變更,ajax 還有 timeout 都會觸發(fā) $apply(),后者才會去調(diào)用$digest。
一.$watch對象
watch ={
name:name // 監(jiān)聽到的對象
getNewValue: function($scope){
}//獲取到的新數(shù)據(jù)
listener:function(newValue,oldValue){
} //將新數(shù)據(jù)和舊數(shù)據(jù)進(jìn)行比較,進(jìn)行操作。
}
getNewValue() 可以得到當(dāng)前$scope 上的最新值,listener 函數(shù)得到新值和舊值并進(jìn)行一些操作。
1.創(chuàng)建$scope監(jiān)聽
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();
}
}
}