$Watch:(監聽一個model,當一個model每次改變時,都會觸發第二個函數)
$watch('watchFn',watchAction,deepWatch)
watchFn:帶有Angular 表達式或者函數的字符串,它會返回被監控的數據模型的當前值。
watchAction: 一個函數function(newValue,oldValue){},當watchFn 發生變化時會被調用
deepWatch:默認為false,監聽數組的某個元素或者對象的屬性時設置為true;
監控一個屬性:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form>
<div class="form-group">
<input ng-model="name" />{{name}}
<p>改變次數{{count}}</p>
</div>
</form>
</div>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope){
$scope.name = '橘子';
$scope.count = 0;
$scope.$watch('name', function (newValue, oldValue) {
$scope.count++;
if($scope.count >5){
$scope.name = '蘋果';
}
});
});
</script>
</body>
</html>
監控一個對象(deepWidth為true)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form>
<div class="form-group">
<input ng-model="Data.name" />{{Data.name}}
<p>改變次數{{count}}</p>
</div>
</form>
</div>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope){
$scope.Data = { name: '橘子' };
$scope.count = 0;
$scope.$watch('Data', function (newValue, oldValue) {
if(newValue == oldValue)
return;
$scope.count++;
if($scope.count >5){
$scope.Data.name = '蘋果';
}
}, true);
});
</script>
</body>
</html>
