$ watchCollection does not work with array

I use $ watchCollection to view changes in the length of an array. But it doesn't seem to work when I add any element to the array. Where am I mistaken?

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);
  })

});

Demo: http://plnkr.co/edit/dSloJazZgr3mMevIHOe8?p=preview

+4
source share
2 answers

You should pass the expression as the first variable in $watchCollection, not the object:

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

plnkr example .

+9
source

I had another problem. Consider the following:

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

and I had a different controller

app.controller('RelatedCtrl', function($scope) {
  unwatch = $scope.$watch('totallyUnrelated', function() {
    [...];
  },true);
});

the problem was that the assignment is the unwatch = [...];same aswindow.unwatch = [...];

, , ...

var unwatch = [...];, ( js, angular).

.

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

All Articles