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');
})
}
}
}]);
答案 0 :(得分:1)
默认情况下,$ watch方法仅监视对象的第一级/图层上的更改,以观察必须添加true作为第二个参数的嵌套值:
scope.$watch('items', function(){
scope.total = Cart.total();
}, true);