關(guān)于angular js_$watch監(jiān)控屬性和對象詳解
$Watch:(監(jiān)聽一個model,當(dāng)一個model每次改變時,都會觸發(fā)第二個函數(shù))
$watch('watchFn',watchAction,deepWatch)
watchFn:帶有Angular 表達(dá)式或者函數(shù)的字符串,它會返回被監(jiān)控的數(shù)據(jù)模型的當(dāng)前值。
watchAction: 一個函數(shù)function(newValue,oldValue){},當(dāng)watchFn 發(fā)生變化時會被調(diào)用
deepWatch:默認(rèn)為false,監(jiān)聽數(shù)組的某個元素或者對象的屬性時設(shè)置為true;
監(jiān)控一個屬性:
<!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>改變次數(shù){{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>
監(jiān)控一個對象(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>改變次數(shù){{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>
以上這篇關(guān)于angular js_$watch監(jiān)控屬性和對象詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Angular路由 ng-route和ui-router的區(qū)別
這篇文章主要介紹了詳解Angular路由 ng-route和ui-router的區(qū)別,分別介紹了兩種路由的用法和區(qū)別,有興趣的可以了解一下2017-05-05
關(guān)于Angularjs中跨域設(shè)置白名單問題
這篇文章主要介紹了Angularjs中關(guān)于跨域設(shè)置白名單問題,需要的朋友可以參考下2018-04-04
angular學(xué)習(xí)之從零搭建一個angular4.0項目
本篇文章主要介紹了從零搭建一個angular4.0項目,主要用到的工具angular4.0、angular-cli、npm(v3.10.8)、node(v6.2.0),有興趣的可以了解一下2017-07-07
AngularJs實(shí)現(xiàn)分頁功能不帶省略號的代碼
這篇文章主要介紹了AngularJs實(shí)現(xiàn)分頁功能不帶省略號的代碼的相關(guān)資料,非常不錯具有參考借鑒價值,感興趣的朋友一起看看吧2016-05-05
AngularJS學(xué)習(xí)第一篇 AngularJS基礎(chǔ)知識
這篇文章主要介紹了AngularJS學(xué)習(xí)第一篇,分享了有關(guān)AngularJS的基礎(chǔ)知識,主要包括指令、過濾器等,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-02-02

