$ watchCollection未在对象更改时触发

时间:2014-04-23 15:11:01

标签: angularjs angularjs-scope

我一直试图找出为什么在对象更改时没有触发watchCollection?

.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;

})

这是指令:

.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!");

            });

        }
    }
})

任何提示都将不胜感激!

谢谢!

2 个答案:

答案 0 :(得分:1)

假设其他一切都正确的话试试这个:

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

而不是

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

$watchCollection可以采用一个字符串(角度表达式)来计算数组或一个对象或一个返回值的函数。

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

答案 1 :(得分:-1)

抱歉,这是一个错字。参数应该是函数或字符串形式的表达式。

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



});