【问题标题】:angular $scope.$watch on array calling update function角度 $scope.$watch 对数组调用更新函数
【发布时间】:2016-08-05 04:43:35
【问题描述】:

my plunk 中,我有一个整数数组,我已将 $scope.$watch 附加到该数组。当我更新数组时,我的 $scope.$watch 不会触发 console.log。为什么我的 console.log 没有被调用?

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angularjs@1.5.0" data-semver="1.5.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.2/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="test" ng-controller="testArray">

    <div ng-repeat="item in MyArray track by $index"> {{item}}</div>
    <button ng-click="add()">testing Add</button>
  </body>

</html>
<script type="text/javascript">
    'use strict';
    var app = angular.module('test', []);

    app.controller('testArray',['$scope',function($scope){

      $scope.MyArray = [1,2,3,4]

      $scope.add = function(){
        $scope.MyArray.push($scope.MyArray.length+1);
      }
    $scope.$watch('MyArray' , function(){
      console.log($scope.MyArray);
    })
    }]);

</script>

【问题讨论】:

    标签: javascript arrays angularjs angularjs-scope angularjs-watch


    【解决方案1】:

    你可以使用$watchCollection,只要在$watch函数中提供true选项,它就会比deep watcher便宜。

    $scope.$watchCollection('MyArray' , function(){
        console.log($scope.MyArray);
    })
    

    $watchCollection() 深入一层并对集合中的顶级项目执行额外的浅层引用检查。

    如果您有非常大的阵列需要密切关注,那么请不要选择 $watchtrue(深度观察者)。对于1000/2000 记录,您会在角度绑定中感到滞后。所以首选的方法是尽可能地避免watcher直接选择$watchCollection

    【讨论】:

      【解决方案2】:

      把你的代码改成

      $scope.$watch('MyArray' , function(){
          console.log($scope.MyArray);
      }, true)
      

      查看documentation,您会看到第三个参数表明$watch 方法将使用对象相等来确定您的数组是否已更改。表示angular会使用支持数组比较的angular.equals方法,例如

      【讨论】:

      • 如果您将第三个参数设置为 trus,则意味着 angular 将对对象进行深度监视
      • 我决定接受@pankajParkers 的回答,因为 watchCollection 的内存性能优于使用 angular.copy
      • @RenanLopesFerreira & gh9 谢谢大家。如果您涵盖deep watcher 的性能相关内容,我不会添加答案。因此,与其编辑您的答案。我确实添加了新答案。 :-)
      • @PankajParkar 我不知道 $watchCollection,所以,谢谢!
      猜你喜欢
      • 2014-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多