如果想在controller裏面隨時監聽一個值的變化那就用$watch
<label><strong>$watch:</strong></label> |
<input
type= "text" ng-model= "name" /> |
$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" /> |
<label><strong>$watchGroup:</strong></label> |
<input
type= "text" ng-model= "two" /> |
$scope.$watchGroup([ "one" , "two" ], function (newVal,oldVal)
{ |
console.log( "new:" +newVal, "old:" +oldVal); |
$watchCollection是爲一堆數據進行監聽
<p
style= "margin-top:
20px" ><strong>$watchCollection:</strong></p> |
<li
ng-repeat= "d
in lang" >{{d}}</li> |
$scope.lang
= [ 'C/C++' , 'Java' , 'C#' , 'Python' ]; |
$scope.$watchCollection( 'lang' , function (newVal,
oldVal) { |
console.log( "new:" +newVal, "old:" +oldVal) |
現在可以做個測試,使用$timeout二秒後發生變化
$scope.lang
= [ 'JavaScript' , 'Html5' , 'Css3' , 'Angularjs' ]; |
點擊查看完整代碼