- 論壇徽章:
- 0
|
簡(jiǎn)介
首先apply方法會(huì)觸發(fā)evel方法,當(dāng)evel方法解析成功后,會(huì)去觸發(fā)digest方法,digest方法會(huì)觸發(fā)watch方法。
在digest執(zhí)行時(shí),如果watch觀察的的value與上一次執(zhí)行時(shí)不一樣時(shí),就會(huì)被觸發(fā)。
AngularJS內(nèi)部的watch實(shí)現(xiàn)了頁(yè)面隨model的及時(shí)更新。
$watch方法在用的時(shí)候主要是手動(dòng)的監(jiān)聽(tīng)一個(gè)對(duì)象,但對(duì)象發(fā)生變化時(shí)觸發(fā)某個(gè)事件。】
語(yǔ)法
$watch(watchFn,watchAction,deepWatch)
watchFn:該參數(shù)是一個(gè)帶有Angular 表達(dá)式或者函數(shù)的字符串,它會(huì)返回被監(jiān)控的數(shù)據(jù)模型的當(dāng)前值。這個(gè)表達(dá)式將會(huì)被執(zhí)行很多次,所以你要保證它不會(huì)產(chǎn)生其他副作用。也就是說(shuō),要保證它可以被調(diào)用很多次而不會(huì)改變狀態(tài);谕瑯拥脑颍O(jiān)控表達(dá)式應(yīng)該很容易被計(jì)算出來(lái)。如果你使用字符串傳遞了一個(gè)Angular 表達(dá)式,那么它將會(huì)針對(duì)調(diào)用它的那個(gè)作用域中的對(duì)象而執(zhí)行。
watchAction(newValue,oldValue,scope):這是一個(gè)函數(shù)或者表達(dá)式,當(dāng)watchFn 發(fā)生變化時(shí)會(huì)被調(diào)用。如果是函數(shù)的形式,它將會(huì)接收到watchFn 的新舊兩個(gè)值,以及作用域?qū)ο蟮囊。其函?shù)簽名為function(newValue, oldValue, scope)。
deepWatch:如果設(shè)置為true,這個(gè)可選的布爾型參數(shù)將會(huì)命令A(yù)ngular 去檢查被監(jiān)控對(duì)象的每個(gè)屬性是否發(fā)生了變化。如果你想要監(jiān)控?cái)?shù)組中的元素,或者對(duì)象上的所有屬性,而不只是監(jiān)控一個(gè)簡(jiǎn)單的值,你就可以使用這個(gè)參數(shù)。由于Angular 需要遍歷數(shù)組或者對(duì)象,如果集合比較大,那么運(yùn)算負(fù)擔(dān)就會(huì)比較重。
$watch會(huì)返回一個(gè)函數(shù),想要注銷(xiāo)這個(gè)watch可以使用函數(shù).- var dereg = $scope.$watch('someModel.someProperty', callbackOnChange());
- dereg();
復(fù)制代碼 用法- <h3>watch簡(jiǎn)單數(shù)據(jù)類(lèi)型</h3>
- <div ng-controller="ng-watch">
- <input type="text" ng-model="num"><br/>
- <span ng-bind="'變化前的值-'+preVal"></span><br/>
- <span ng-bind="'變化后的值-'+val"></span><br/>
- <label ng-bind="'變化次數(shù)-'+count"></label>
- </div>
- m1.controller("ng-watch",["$scope",function($sc){
- $sc.num = 0;
- $sc.count = 0;
- $sc.preVal = "";
- $sc.val = "";
- $sc.$watch("num",function(newValue,oldValue){
- if(newValue!==oldValue){
- $sc.preVal = oldValue;
- $sc.val = newValue;
- $sc.count++;
- }
- });
- }]);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- <h3>watch對(duì)象</h3>
- <div ng-controller="ng-watch2">
- <input type="text" ng-model="o.num"><br/>
- <span>{{'變化前的值-'+preObj}}</span><br/>
- <span>{{'變化后的值-'+obj}}</span><br/>
- <label ng-bind="'變化次數(shù)-'+count"></label>
- </div>
- m1.controller("ng-watch2",["$scope",function($sc){
- $sc.o = {"num": 0};
- $sc.count = 0;
- $sc.preObj = "";
- $sc.obj = "";
- $sc.$watch('o',function(newValue,oldValue){
- if(newValue!==oldValue){
- $sc.preObj = oldValue;
- $sc.obj = newValue;
- $sc.count++;
- }
- },true);
- }]);
復(fù)制代碼 |
|