2014-04-08 19 views
0

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

默认情况下,$腕表方法只手表为对象的第一级/层上的变化,看嵌套值,您必须添加真正作为第二个参数:

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

谢谢您。我只是忘记了默认的浅层'$ watch'不关心数组中有多少个元素。现在你已经提醒我我已经意识到'$ watchCollection'就足够了。 – Tules