$ watch在服务变量发生变化时不会触发

时间:2014-04-08 16:45:45

标签: angularjs angularjs-directive

cart指令有一个$watch,可以监视scope.items进行更改,而这些更改又会从Cart服务中引用。手表永远不会开火。我可以通过重新计算mouseenter来实现它,但我想要一个更强大的解决方案。

.directive('cart', ['Cart', 'Catalogue', function(Cart, Catalogue){
return {
    templateUrl: './templates/cart.html',
    restrict: 'E',
    link: function(scope, element, attrs){
        scope.items = Cart.getItems;
        scope.$watch('items', function(){
            scope.total = Cart.total();
        });
        scope.catalogue = Catalogue;            
        element.bind('mouseenter', function(){
            //Can make it work by doing it inside here, but that doesn't seem right
            //scope.total = Cart.total();
            scope.$apply('showDropdown = true');
        });
        element.bind('mouseout', function(){    
            scope.$apply('showDropdown = false');
        })
    }
}
}]);

1 个答案:

答案 0 :(得分:1)

默认情况下,$ watch方法仅监视对象的第一级/图层上的更改,以观察必须添加true作为第二个参数的嵌套值:

scope.$watch('items', function(){
    scope.total = Cart.total();
}, true);