Manoz
Manoz

Reputation: 6587

Value not updated

I am new to angular and still struggling with basics.

I've a cart icon in my menu with the preset value to 0 at first load.

In the product list I have a button to every product to say 'AddToCart'. So what I want is-

I want to update the cart value whenever I click to AddToCart button. However initial value of cart is being setup by angular, But I am not able to update it further.

Here is the code-

var app = angular.module("productsApp", [])
.factory("sharedService", ['$rootScope', function ($rootScope) {
        var sharedServiceRef = {
            cart: 0,
            setCartValue: function (product) {
                if (product) {
                    this.cart = this.cart + 1;
                    sharedServiceRef.cart = this.cart;
                }
                else {
                    sharedServiceRef.cart = 0;
                }
                console.log(sharedServiceRef.cart);
            }
        };
        return sharedServiceRef;
    }]);


function ProductListController($scope, sharedService) {
    $scope.addItemToCart = function (product) {
        sharedService.setCartValue(product);
    }
}

function CartController($scope, sharedService) {
    $scope.cart = sharedService.cart;
}

At initial load of page it sets the value of cart in the view-

<div ng-controller="CartController">
       {{cart}}
    </div>

And when I change the value in another controller and set it -

function ProductListController($scope, sharedService) {
    $scope.addItemToCart = function (product) {
        sharedService.setCartValue(product);
    }
}

It doesn't update the cart value, It remains 0 at first place.

How do I update a value in angular?

Edit This is my view from where add button is being called-

<div ng-controller="ProductListController">
    <div ng-repeat="product in products">
        <span>
            $ {{product.salePrice}}
        </span>
        <div>
            <a ng-click="addItemToCart(product)">
                Add To Cart
            </a>
        </div>
    </div>
</div>

Upvotes: 1

Views: 303

Answers (1)

Manuel Salguero
Manuel Salguero

Reputation: 36

Your error was not an angular error but a javascript one.

When you do this: $scope.cart = sharedService.cart;

you are assigning the value not a reference, in other words it is a copy of the original values, changes done to sharedService.cart will not affect the variable $scope.cart

In javascript primitive variables are assigned by value value while objects by reference, so what you can do is assign an object to $scope.cart

Here is a plunker with an example of it working https://plnkr.co/edit/MKSofFcgEWMjwQaOvLsP?p=preview

Upvotes: 2

Related Questions