user2696466
user2696466

Reputation: 740

how to refresh counter value of one controller from another angularjs

I have a cart counter which is in header controller. and a add to cart button which is in image view controller. I want to set cart counter from the image view controller. SO every time add to cart is clicked it changes the cart value.

Header controller :

 decorpotCtrls.controller('DecorpotCtrl', [ '$scope', '$routeParams', 'cart',
    function($scope, $routeParams, cart) {
        $scope.cartCounter = cart.getCartCounter();
    } ]);

Image Controller : -

  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);

        };

    } ]);

cart Html : -

  <i class="glyphicon glyphicon-shopping-cart" aria-hidden="true"></i> Cart({{cartCounter}})

add to cart from image controller -

 <div id="addToCart" class="btn btn-primary btn-lg buyNCartButton" ng-click="addToCart(groupid)">Add To Cart</div>

cart service -

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;
        }

    };
});

Upvotes: 2

Views: 968

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

You could do one thing set method reference to $scope.cartCounter like

$scope.cartCounter = cart.getCartCounter;

Then on HTML you could call that method like cartCounter() that will get evaluated on each digest.

<i class="glyphicon glyphicon-shopping-cart" aria-hidden="true"></i> 
Cart({{cartCounter()}})

Upvotes: 4

GrandFelix
GrandFelix

Reputation: 551

Use $rootScope in controller. All $scopes are "childs" of $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);

    };

} ]);

Upvotes: 0

Related Questions