angularjs的$watch、$watchGroup、$watchCollection使用方式(轉載)

如果想在controller里面隨時監聽一個值的變化那就用<code>$watch</code>

<p>  
<label><strong>$watch:</strong></label>
<input type="text" ng-model="name" />
</p>
$scope.$watch("name",function(newVal,oldVal){    
        console.log("new:"+newVal,"old:"+oldVal)
});

以上代碼實現監聽<code>name</code>屬性值的變化,但是有個缺點假如要監聽很多個屬性值,就要寫很多個<code>$watch</code>為了解決上面的問題,可以使用<code>$watchGroup</code>,這個監聽器是把多個屬性使用數組的形式作為第一個參數傳入

<p style="margin-top: 20px">  
<label><strong>$watchGroup:</strong></label>
<input type="text" ng-model="one" />
</p>
<p>    
<label><strong>$watchGroup:</strong></label>    
<input type="text" ng-model="two"/>
</p>
$scope.$watchGroup(["one","two"], function (newVal,oldVal) {
        console.log("new:"+newVal,"old:"+oldVal);    
        //注意:newVal與oldVal都返回的是一個數組
});

<code>$watchCollection</code>是為一堆數據進行監聽

<p style="margin-top: 20px"><strong>$watchCollection:</strong></p>
<ul>
<li ng-repeat="d in lang">{dbzftqm}</li>
</ul>
$scope.lang = ['C/C++', 'Java', 'C#', 'Python'];
$scope.$watchCollection('lang', function (newVal, oldVal) {    
        console.log("new:"+newVal,"old:"+oldVal)
});

現在可以做個測試,使用<code>$timeout</code>二秒后發生變化

$timeout(function(){
        $scope.lang = ['JavaScript', 'Html5', 'Css3', 'Angularjs'];
},2000);

點擊查看完整代碼

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容