Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$watchCollection not working on array

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

like image 704
user1184100 Avatar asked Feb 15 '23 04:02

user1184100


1 Answers

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.

like image 70
John Ledbetter Avatar answered Feb 17 '23 03:02

John Ledbetter