[英]Angular service variable not updated in the view
I have the following service: 我有以下服务:
app.service('Cart', function() {
this.data = [];
this.addFont = function(font) { return this.data.push(font) };
this.removeFont = function(i) { return this.data.splice(i, 1); };
this.count = function() { return this.data.length; };
});
And the following directive, that displays a cart icon with the number of items in it: 以下指令显示购物车图标,其中包含物品数量:
app.directive('cartButton', ['Cart', function(Cart) {
return {
restrict: 'E',
replace: true,
template: '<button class="selection"><i class="fa fa-shopping-cart"></i> {{ Cart.count() }}</button>'
};
}]);
But the counter doesn't work, and there is no error. 但是计数器不起作用,也没有错误。
How to access Cart.count()
inside my directive? 如何在我的指令中访问Cart.count()
?
Try this: 尝试这个:
return {
restrict: 'E',
replace: true,
template: '<button class="selection"><i class="fa fa-shopping-cart"></i> {{ Cart.count() }}</button>',
link: function(scope) {
scope.Cart= Cart;
}
};
You need to assign it to scope. 您需要将其分配给作用域。
Angular expressions are evaluated against the scope. 角度表达式将根据范围进行评估。
Try to set a function on the scope which will get the count from Cart
: 尝试在示波器上设置一个将从Cart
计数的函数:
return {
restrict: 'E',
replace: true,
template: '<button class="selection"><i class="fa fa-shopping-cart"></i> {{ getCartCount() }}</button>',
link: function(scope) {
scope.getCartCount = function() {
return Cart.count();
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.