Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript $watchCollection在阵列上不工作_Javascript_Angularjs - Fatal编程技术网

Javascript $watchCollection在阵列上不工作

Javascript $watchCollection在阵列上不工作,javascript,angularjs,Javascript,Angularjs,我使用$watchCollection监视数组长度的变化。但当我向数组中添加任何项时,它似乎不起作用。我哪里做错了 var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.count; $scope.Items = { "Cars" : [ { "id" : 1, "

我使用$watchCollection监视数组长度的变化。但当我向数组中添加任何项时,它似乎不起作用。我哪里做错了

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.count;
  $scope.Items = {
      "Cars" : [
          {
              "id" : 1,
              "name" : "Mercedes"
          },
          {
              "id": 2,
              "name" : "Ferrari"
          }

      ],
      "Bikes" : [
           {
              "id" : 1,
              "name" : "Ducati"
          },
          {
              "id": 2,
              "name" : "Yamaha"
          } 

      ]
  }

  $scope.addCar = function() {
    $scope.Items.Cars.push({
        'id' : 3,
        "name" : "random name"
    })
  }

  $scope.$watchCollection($scope.Items.Cars, function(newNames, oldNames) {
    $scope.count = $scope.Items.Cars.length;
    console.log($scope.count);
  })

});

演示:

您应该将表达式作为第一个变量传递给,而不是对象:

$scope.$watchCollection('Items.Cars', function(newNames, oldNames) {
  $scope.count = $scope.Items.Cars.length;
  console.log($scope.count);
})

.

我有一个不同的问题。考虑以下事项:

app.controller('MainCtrl', function($scope) {
  unwatch = $scope.$watch('variableName', function() {
    [...];
  },true);
  setInterval(function() {
    $scope.variable++;
    $scope.$apply();
  }, 1000);
});
我还有另一个控制器

app.controller('RelatedCtrl', function($scope) {
  unwatch = $scope.$watch('totallyUnrelated', function() {
    [...];
  },true);
});
问题是赋值
unwatch=[…]
window.unwatch=[…]相同

因此,当另一个控制器决定取消跟踪时,它实际上是在不同范围内取消跟踪观察者

解决方案 使用
var unwatch=[…]
使变量成为当前函数作用域的局部变量(js作用域,而不是角度作用域)

e、 g

app.controller('MainCtrl', function($scope) {
  var unwatch = $scope.$watch('variableName', function() {
    [...];
  },true);
  setInterval(function() {
    $scope.variable++;
    $scope.$apply();
  }, 1000);
});