2014-04-08 18 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