如果想在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);