I'm using $watchCollection to watch for changes in an array length. But it doesn't seem to work when I add any item onto the array. Where am I going wrong ?
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
You should pass an expression as the first variable to $watchCollection, not an object:
$scope.$watchCollection('Items.Cars', function(newNames, oldNames) {
  $scope.count = $scope.Items.Cars.length;
  console.log($scope.count);
})
plnkr example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With