angular之$watch() $watchGroup()和$watchCollection()

$watchjavascript

$watch主要是用來監聽一個對象,在對象發生變化時觸發某個事件。 
用法:
html

$scope.$watch(watchFn,watchAction, deepWatch)

接下來說一下這幾個參數:java

 

參數 說明
watchFn angular表達式或函數的字符串
watchAction(newValue,oldValue,scope) watchFn發生變化會被調用
deepWatch 可選的布爾值命令檢查被監控的對象的每一個屬性是否發生變化

注意:deepWatch爲布爾值,true時能夠用來監測對象,false通常是用來監測個別元素。watchFn通常是在html中的ng-model標籤。 
舉個例子:
數組

<body ng-controller="MainCtrl">
  <input ng-model="user.name" />
  Name updated: {{updated}} times.
</body>
app.controller('MainCtrl', function($scope) {
  $scope.user = { name: "Fox" };

  $scope.updated = 0;

  $scope.$watch('user', function(newValue, oldValue) {
    if (newValue === oldValue) { return; }
    $scope.updated++;
  }, true);  //必須有true
});

$watch默認狀況下是比較兩個對象所引用的是否相同,當咱們在監聽$scope.user時,若是改變$scope.user.name時,對$scope.user的引用是不會改變的,此時檢測不到值的變化。可是在$watch中加入第三個參數爲true時,就能每次去比較對象的值而不是引用。app

 

$watchGroup()和$watchCollection()

因爲watch()深比較性能較差,angular還提供了$watchGroup([watchExp], listener)和$watchCollection(obj, listener) 方法來分別監聽數組和對象。 
$watchGroup: 
實際上是使用watch監聽一組watchExp,因此watchGroup不支持深比較 
$watchCollection: 
比$watch進一步,可是基於性能考慮它只向內關注1層,對數組從新賦值,或是對數組元素進行新增、刪除、修改時,回調會被調用,注意只要是修改就會調用,若是給數組賦的值和以前同樣也會觸發回調。若是某個數組元素內部的某個屬性被更新時,回調不會被調用。 
看個例子:
函數

<div ng-controller="ctrl">

    <!-- $watch -->
    <div>
      <input type="text" ng-model="value1"/>
    </div>
    <div ng-bind="w1"></div>
    
    <!-- $watchGroup -->
    <div>
      <input type="text" ng-model="value2"/>
      <input type="text" ng-model="value3"/>
    </div>
    <div ng-bind="w2"></div>
    
    <!-- $watchCollection -->
    <ul>
      <li ng-repeat="v in arr" ng-bind="v"></li>
    </ul>
    <div ng-bind="w3"></div>
  </div>
angular.module('myApp', [])
        .controller("ctrl", ["$scope", "$timeout", function ($scope, $timeout) {
        
          // $watch
          var watcher = $scope.$watch("value1", function (newVal, oldVal) {
            $scope.w1 = "$watch--" + "new:" + newVal + ";" + "old:" + oldVal;
            if (newVal == 'clear') {//設置一個註銷監聽的條件
              watcher(); //註銷監聽
            }
          });
          
          
          // $watchGroup
          $scope.$watchGroup(["value2", "value3"], function (newVal, oldVal) {
            //注意:newVal與oldVal都返回的是一個數組
            $scope.w2 = "$watchGroup--" + "new:" + newVal + ";" + "old:" + oldVal;
          });
          
          
          //  $watchCollection
          $scope.arr = ['nick', 'ljy', 'ljj', 'zhw'];
          $scope.$watchCollection('arr', function (newVal, oldVal) {
            $scope.w3 = "$watchCollection--" + "new:" + newVal + ";" + "old:" + oldVal;
          });
          $timeout(function () {
            $scope.arr = ['my', 'name', 'is', 'nick'];
          }, 2000);
        }]);
相關文章
相關標籤/搜索