AngularJS之watch

簡介javascript

    首先apply方法會觸發evel方法,當evel方法解析成功後,會去觸發digest方法,digest方法會觸發watch方法。java

    在digest執行時,若是watch觀察的的value與上一次執行時不同時,就會被觸發。數組

    AngularJS內部的watch實現了頁面隨model的及時更新。app

    $watch方法在用的時候主要是手動的監聽一個對象,但對象發生變化時觸發某個事件。】函數

語法spa

    $watch(watchFn,watchAction,deepWatch)對象

        watchFn:該參數是一個帶有Angular 表達式或者函數的字符串,它會返回被監控的數據模型的當前值。這個表達式將會被執行不少次,因此你要保證它不會產生其餘反作用。也就是說,要保證它能夠被調用不少次而不會改變狀態。基於一樣的緣由,監控表達式應該很容易被計算出來。若是你使用字符串傳遞了一個Angular 表達式,那麼它將會針對調用它的那個做用域中的對象而執行。blog

     watchAction(newValue,oldValue,scope):這是一個函數或者表達式,當watchFn 發生變化時會被調用。若是是函數的形式,它將會接收到watchFn 的新舊兩個值,以及做用域對象的引用。其函數簽名爲function(newValue, oldValue, scope)。事件

        deepWatch:若是設置爲true,這個可選的布爾型參數將會命令Angular 去檢查被監控對象的每一個屬性是否發生了變化。若是你想要監控數組中的元素,或者對象上的全部屬性,而不僅是監控一個簡單的值,你就可使用這個參數。因爲Angular 須要遍歷數組或者對象,若是集合比較大,那麼運算負擔就會比較重。ip

    $watch會返回一個函數,想要註銷這個watch可使用函數.
  var dereg = $scope.$watch('someModel.someProperty', callbackOnChange());
  dereg();

用法 

    <h3>watch簡單數據類型</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="'變化次數-'+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++;
            }
       });
    }]);
    <h3>watch對象</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="'變化次數-'+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);
    }]);

效果:http://runjs.cn/detail/vnlh0eny

相關文章
相關標籤/搜索