Angularjs $watch在服务变量更改时不触发
Angularjs $watch在服务变量更改时不触发,angularjs,angularjs-directive,Angularjs,Angularjs Directive,cart指令有一个$watch,它监视范围。项目的变化,而这些变化又从cart服务中引用。手表从不点火。我可以通过在mouseenter上重新计算来让它工作,但我想要一个更健壮的解决方案 .directive('cart', ['Cart', 'Catalogue', function(Cart, Catalogue){ return { templateUrl: './templates/cart.html', restrict: 'E', link: function
cart
指令有一个$watch
,它监视范围。项目
的变化,而这些变化又从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');
})
}
}
}]);
默认情况下,$watch方法仅监视对象第一个级别/层上的更改,若要监视嵌套值,必须将true添加为第二个参数:
scope.$watch('items', function(){
scope.total = Cart.total();
}, true);
非常感谢。我只是忘记了默认的浅层
$watch
并不关心数组中有多少个元素。既然你提醒了我,我已经意识到,$watchCollection
就足够了。