Search code examples
angularjsangularjs-scope

$watchCollection not being triggered on object change


I've been trying to figure out why watchCollection isn't not triggered on object change ?

.factory('Products', function($http, $timeout){

    function Products(data){

        if (data) {
            this.setData(data);
        };

    };

    Products.prototype = {

        selected: {},

        setData: function(data) {
            angular.extend(this, { categories: data });
        },

        load: function() {

            var scope = this;

            $http
                .get('products.php?option=get_categories')
                .success(function(data) {

                    scope.setData(data);

                });

        }

    };

    var instanceManager = {

        products: false,

        get: function(){

            if (!this.products){

                this.products = new Products();

                this.products.load();

            };

            return this.products;

        }

    };

    return instanceManager;

})

Here's the directive:

.directive("foo", function(Products){
    return {
        restrict: 'A',
        link: function(scope, el, attrs) {

            scope.products = Products.get();

            scope.$watchCollection(scope.products, function(newValue, oldValue){

                if (newValue == oldValue) {
                    return;
                };

                console.log("Hello!");

            });

        }
    }
})

Solution

  • Assuming everything else is correct try this:

    scope.$watchCollection('products', function(newValue, oldValue){

    instead of

    scope.$watchCollection(scope.products, function(newValue, oldValue){

    $watchCollection can take either a string (angular expression) which evaluates to an array or an object or a function which returns a value.

    https://docs.angularjs.org/api/ng/type/$rootScope.Scope