[英]How to pass the value to one controller to another controller in angularjs?
[英]how to refresh counter value of one controller from another angularjs
我在標題控制器中有一個購物車計數器。 以及圖像視圖控制器中的添加到購物車按鈕。 我想從圖像視圖控制器設置購物車計數器。 因此,每次單擊添加到購物車都會更改購物車的價值。
標頭控制器:
decorpotCtrls.controller('DecorpotCtrl', [ '$scope', '$routeParams', 'cart',
function($scope, $routeParams, cart) {
$scope.cartCounter = cart.getCartCounter();
} ]);
圖像控制器:-
decorpotCtrls.controller('ImageViewController', [
'$scope',
'$routeParams',
'imageView',
'$auth',
'cart',
function($scope, $routeParams, imageView, $auth, cart) {
$scope.addToCart = function(groupid) {
console.log($auth.isAuthenticated());
return cart.addToCart(groupid);
};
} ]);
購物車HTML:-
<i class="glyphicon glyphicon-shopping-cart" aria-hidden="true"></i> Cart({{cartCounter}})
從圖片控制器添加到購物車-
<div id="addToCart" class="btn btn-primary btn-lg buyNCartButton" ng-click="addToCart(groupid)">Add To Cart</div>
購物車服務-
services.service('cart', function($http){
var counter =0 ;
sessionStorage.setItem('cartCounter', counter);
//var
return {
checkout : function(){
},
addToCart : function(gruopid){
counter++;
return counter;
},
getCartCounter : function(){
return counter;
}
};
});
您可以對$scope.cartCounter
做一件事設置方法引用,例如
$scope.cartCounter = cart.getCartCounter;
然后在HTML上,您可以調用諸如cartCounter()
類的方法,該方法將在每個摘要中進行評估。
<i class="glyphicon glyphicon-shopping-cart" aria-hidden="true"></i>
Cart({{cartCounter()}})
在控制器中使用$ rootScope。 所有$ scope都是$ rootScope的“子級”。
decorpotCtrls.controller('ImageViewController', [
'$rootScope',
'$scope',
'$routeParams',
'imageView',
'$auth',
'cart',
function($scope,$rootScope, $routeParams, imageView, $auth, cart) {
$scope.addToCart = function(groupid) {
$rootScope.counter++;
console.log($auth.isAuthenticated());
return cart.addToCart(groupid);
};
} ]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.