$watch、$watchGroup、$watchCollection三者怎么在Angular中使用

$watch、$watchGroup、$watchCollection三者怎么在Angular中使用?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于成都網(wǎng)站建設(shè)、網(wǎng)站制作、漢壽網(wǎng)絡(luò)推廣、小程序定制開發(fā)、漢壽網(wǎng)絡(luò)營銷、漢壽企業(yè)策劃、漢壽品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)為所有大學生創(chuàng)業(yè)者提供漢壽建站搭建服務(wù),24小時服務(wù)熱線:028-86922220,官方網(wǎng)址:bm7419.com

?  1,原型:$watch: function(watchExp, listener, objectEquality, prettyPrintExpression){};

?  2,參數(shù):watchExp(必須):{(function()|string)},可以字符串表達式,也可以帶當前scope為參數(shù)的函數(shù)

?    - `string`: Evaluated as {@link guide/expression expression}

?    - `function(scope)`: called with current `scope` as a parameter.

? 3,參數(shù):listener(必須):function(newVal, oldVal, scope),觀察的表達式變化的時候調(diào)用的函數(shù)。

? 4,參數(shù):objectEquality(非必須):是否監(jiān)視個對象,默認為false

? 5,$scope.$digest().會執(zhí)行所有的同$scope下的$watch。

?     但會出錯$apply already in progress,換了$rootScope也一樣。

?     原因-參考大牛博客:http://blog.csdn.net/aitangyong/article/details/48972643

?     $digest、$apply、$$phase這些屬性或者方法其實都是$scope中的私有的,最好不要使用。

? 6,$watch一個對象。

?    如果要監(jiān)視對象的變化(地址改變),$watch對象名,第三個參數(shù)默認;

?    如果監(jiān)測對象中某一屬性,可以寫user.name的形式,第三個參數(shù)默認;

?     如果監(jiān)測對象中全部屬性,$watch對象名,第三個參數(shù)true;

? 7,$watchGroup,第一個參數(shù)是一個表達式的數(shù)組或者返回表達式的數(shù)組的函數(shù)。

? 8,$watchCollection;

?     js中數(shù)組也是對象,但按照$watch一個對象的方式,只有數(shù)組引用變了才能監(jiān)聽變化,增加刪除$watch監(jiān)聽不到,所以就有了$watchCollection。

?     function(obj, listener):第一個參數(shù)必須對象或者返回對象的函數(shù)。

?9,注銷$watch

?         $watch函數(shù)返回一個注銷監(jiān)聽的函數(shù),太多的$watch將會導致性能問題,$watch如果不再使用,我們最好將其釋放掉。

一、使用方法

html

<div ng-controller="ctrl">
    <h3>$watch</h3>
    <div>
      <input type="text" ng-model="value1"/>
    </div>
    <div ng-bind="w1"></div>
    <h3>$watchGroup</h3>
    <div>
      <input type="text" ng-model="value2"/>
      <input type="text" ng-model="value3"/>
    </div>
    <div ng-bind="w2"></div>
    <h3>$watchCollection</h3>
    <ul>
      <li ng-repeat="v in arr" ng-bind="v"></li>
    </ul>
    <div ng-bind="w3"></div>
  </div>

js

 angular.module('nickApp', [])
        .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') {//設(shè)置一個注銷監(jiān)聽的條件
              watcher(); //注銷監(jiān)聽
            }
          });
          // $watchGroup
          $scope.$watchGroup(["value2", "value3"], function (newVal, oldVal) {
            //注意:newVal與oldVal都返回的是一個數(shù)組
            $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);
        }])

二、小案例

html

<h3>小案例</h3>
  <ul>
    <li ng-repeat="item in items.goodsArr">
      <p ng-bind="item.goods"></p>
      <p>
        <span>單價:</span>
        <span ng-bind="item.price"></span>
      </p>
      <div>
        <input type="number" ng-model="item.num">
        <span>個</span>
      </div>
    </li>
  </ul>
  <div>
    <span>總計:</span>
    <span ng-bind="items.sum"></span>
    <span>元</span>
  </div>

js          

 //     小案例
        .factory('watchService', [function () {
          var items = {
            goodsArr: [{
              goods: 'goods1',
              price: 10,
              num: ''
            }, {
              goods: 'goods2',
              price: 20,
              num: ''
            }],
            sum: 0
          };
          return {
            getItemsSave: function () {
              return items;
            }
          };
        }])
        .controller('bodyCtl', ['$scope', 'watchService', function ($scope, watchService) {
          $scope.items = watchService.getItemsSave();
//          這里要監(jiān)聽數(shù)量變化計算綜合
          //一 只監(jiān)聽所有num變化計算總額
          var watchArr = [];
          $scope.items.goodsArr.forEach(function (v, i) {
            watchArr.push("items.goodsArr[" + i + "]['num']");
          });
          $scope.$watchGroup(watchArr, function (newVal, oldVal) { //注意:newVal與oldVal都返回的是一個數(shù)組
            $scope.items.sum = 0;
            $scope.items.goodsArr.forEach(function (v, i) {
              $scope.items.sum += v.price * (v.num > 0 ? v.num : 0);
            });
          });
/*
          //二 這樣寫則監(jiān)聽items.goodsArr所有成員
          $scope.$watch('items.goodsArr', function () {
            $scope.items.sum = 0;
            $scope.items.goodsArr.forEach(function (v, i) {
              $scope.items.sum += v.price * (v.num > 0 ? v.num : 0);
            });
          }, true);*/
        }])

全部代碼

<!DOCTYPE html>
<html ng-app="nickApp">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
  <title>angular之$watch、$watchGroup、$watchCollection</title>
  <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
  <script>
    /*
     * 1,原型:$watch: function(watchExp, listener, objectEquality, prettyPrintExpression){};
     * 2,參數(shù):watchExp(必須):{(function()|string)},可以字符串表達式,也可以帶當前scope為參數(shù)的函數(shù)
     *    - `string`: Evaluated as {@link guide/expression expression}
     *    - `function(scope)`: called with current `scope` as a parameter.
     * 3,參數(shù):listener(必須):function(newVal, oldVal, scope),觀察的表達式變化的時候調(diào)用的函數(shù)。
     * 4,參數(shù):objectEquality(非必須):是否監(jiān)視個對象,默認為false
     * 5,$scope.$digest().會執(zhí)行所有的同$scope下的$watch。
     *  但會出錯$apply already in progress,換了$rootScope也一樣。
     *  原因-參考大牛博客:http://blog.csdn.net/aitangyong/article/details/48972643
     *  $digest、$apply、$$phase這些屬性或者方法其實都是$scope中的私有的,最好不要使用。
     * 6,$watch一個對象。
     *  如果要監(jiān)視對象的變化(地址改變),$watch對象名,第三個參數(shù)默認;
     *  如果監(jiān)測對象中某一屬性,可以寫user.name的形式,第三個參數(shù)默認;
     *  如果監(jiān)測對象中全部屬性,$watch對象名,第三個參數(shù)true;
     * 7,$watchGroup,第一個參數(shù)是一個表達式的數(shù)組或者返回表達式的數(shù)組的函數(shù)。
     * 8,$watchCollection;
     *   js中數(shù)組也是對象,但按照$watch一個對象的方式,只有數(shù)組引用變了才能監(jiān)聽變化,增加刪除$watch監(jiān)聽不到,所以就有了$watchCollection。
     *   function(obj, listener):第一個參數(shù)必須對象或者返回對象的函數(shù)。
     */
    angular.module('nickApp', [])
        .controller("ctrl", ["$scope", "$timeout", function ($scope, $timeout) {
          // $watch
          var watcher = $scope.$watch("value1", function (newVal, oldVal) {
            $scope.w1 = "$watch--" + "new:" + newVal + ";" + "old:" + oldVal;
            /*
             *注銷$watch
             *太多的$watch將會導致性能問題,$watch如果不再使用,我們最好將其釋放掉。
             *$watch函數(shù)返回一個注銷監(jiān)聽的函數(shù),如果我們想監(jiān)控一個屬性,然后在稍后注銷它,可以使用下面的方式:
             */
            if (newVal == 'clear') {//設(shè)置一個注銷監(jiān)聽的條件
              watcher(); //注銷監(jiān)聽
            }
          });
          // $watchGroup
          $scope.$watchGroup(["value2", "value3"], function (newVal, oldVal) {
            //注意:newVal與oldVal都返回的是一個數(shù)組
            $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);
        }])
        //     小案例
        .factory('watchService', [function () {
          var items = {
            goodsArr: [{
              goods: 'goods1',
              price: 10,
              num: ''
            }, {
              goods: 'goods2',
              price: 20,
              num: ''
            }],
            sum: 0
          };
          return {
            getItemsSave: function () {
              return items;
            }
          };
        }])
        .controller('bodyCtl', ['$scope', 'watchService', function ($scope, watchService) {
          $scope.items = watchService.getItemsSave();
//          這里要監(jiān)聽數(shù)量變化計算綜合
          //一 只監(jiān)聽所有num變化計算總額
          var watchArr = [];
          $scope.items.goodsArr.forEach(function (v, i) {
            watchArr.push("items.goodsArr[" + i + "]['num']");
          });
          $scope.$watchGroup(watchArr, function (newVal, oldVal) { //注意:newVal與oldVal都返回的是一個數(shù)組
            $scope.items.sum = 0;
            $scope.items.goodsArr.forEach(function (v, i) {
              $scope.items.sum += v.price * (v.num > 0 ? v.num : 0);
            });
          });
/*
          //二 這樣寫則監(jiān)聽items.goodsArr所有成員
          $scope.$watch('items.goodsArr', function () {
            $scope.items.sum = 0;
            $scope.items.goodsArr.forEach(function (v, i) {
              $scope.items.sum += v.price * (v.num > 0 ? v.num : 0);
            });
          }, true);*/
        }])
  </script>
</head>
<body ng-controller="bodyCtl">
<div ng-view>
  <div ng-controller="ctrl">
    <h3>$watch</h3>
    <div>
      <input type="text" ng-model="value1"/>
    </div>
    <div ng-bind="w1"></div>
    <h3>$watchGroup</h3>
    <div>
      <input type="text" ng-model="value2"/>
      <input type="text" ng-model="value3"/>
    </div>
    <div ng-bind="w2"></div>
    <h3>$watchCollection</h3>
    <ul>
      <li ng-repeat="v in arr" ng-bind="v"></li>
    </ul>
    <div ng-bind="w3"></div>
  </div>
  <h3>小案例</h3>
  <ul>
    <li ng-repeat="item in items.goodsArr">
      <p ng-bind="item.goods"></p>
      <p>
        <span>單價:</span>
        <span ng-bind="item.price"></span>
      </p>
      <div>
        <input type="number" ng-model="item.num">
        <span>個</span>
      </div>
    </li>
  </ul>
  <div>
    <span>總計:</span>
    <span ng-bind="items.sum"></span>
    <span>元</span>
  </div>
</div>
</body>
</html>

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。

當前題目:$watch、$watchGroup、$watchCollection三者怎么在Angular中使用
URL分享:http://bm7419.com/article24/pcejce.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號、用戶體驗、品牌網(wǎng)站建設(shè)、品牌網(wǎng)站設(shè)計外貿(mào)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

微信小程序開發(fā)