angularjs的$watch、$watchGroup、$watchCollection使用方式

angularjs的$watch、$watchGroup、$watchCollection使用方式

如果想在controller裏面隨時監聽一個值的變化那就用$watch

<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)
});

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

<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都返回的是一個數組
});

$watchCollection是爲一堆數據進行監聽

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

現在可以做個測試,使用$timeout二秒後發生變化

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

點擊查看完整代碼

This entry was posted in angularJS by admin. Bookmark the permalink.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章