我想在购物车中添加或删除产品时为我的购物车添加徽章。我正在尝试使用服务但没有运气......
这是我的服务
.factory('sharedCounterService', [function(){
var obj={};
obj.count=0;
obj.addToCartcount=function(){
obj.count+=1;
console.log("COUNT" +obj.count);
};
obj.removeFromCartcount=function(){
obj.count-=1;
console.log("COUNT" +obj.count);
};
return obj;
}]);
控制器
.controller('productCtrl', function($scope,$http,sharedCartService,sharedFilterService,sharedCounterService) {
$scope.addToCart = function(id,image,name,price){
$scope.count=sharedCounterService.addToCartcount;
console.log("COUNT" +sharedCounterService.count);
cart.add(id,image,name,price,1);
};
})
.controller('cartCtrl', function($scope,$rootScope,sharedCartService,$ionicPopup,$state,$http,sharedCounterService) {
$scope.count=sharedCounterService.removeFromCartcount;
console.log("COUNT" +sharedCounterService.count);
})
.controller('mainCtrl', function($scope,sharedCartService,sharedCounterService) {
$scope.count=sharedCounterService;
console.log("COUNT" +sharedCounterService.count);
});
HTML
<a href="#" class="button button-icon ion-android-cart" ><span class="badge badge-assertive">{{count}}</span>
当我控制它时,只有计数器增加购物车价值为0
答案 0 :(得分:0)
在这一行:
$scope.count = sharedCounterService.addToCartcount;
您将addToCartcount
的当前值分配给$scope.count
,但此行执行的任何时间:
obj.count += 1;
或这一行:
obj.count -= 1;
obj.count
会被新值覆盖,但$scope.count
会继续引用其原始值。
要解决此问题,请将整个计数器对象放在您的范围内:
$scope.cartCounter = sharedCounterService;
并在您的视图中引用计数:
<a href="#" class="button button-icon ion-android-cart">
<span class="badge badge-assertive">{{cartCounter.count}}</span>
</a>