2016-02-29 51 views
1

我是新角度和仍與基礎掙扎。價值未更新

我在我的菜單中有一個購物車圖標,第一次加載時預設值爲0。

在產品清單中,我有一個按鈕給每個產品說'AddToCart'。 所以我想要的是 -

我想更新購物車的價值,只要點擊AddToCart按鈕。然而,購物車的初始價值是由角度設置的,但我無法進一步更新它。

這裏是它設置視圖 -

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

的車價值的代碼 -

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

在頁面初始加載當我在另一個控制器更改值,並將其設置 -

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

它不會更新購物車值,它始終保持爲0。

如何更新角度值?

編輯 這是從哪兒添加按鈕被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> 
+0

你可以發佈購物車的東西的HTML端嗎? –

+0

可以幫助嗎? http://stackoverflow.com/questions/15800454/angularjs-the-correct-way-of-binding-to-a-service-properties – Dario

+0

@JohnMc,請看現在 – Manoj

回答

2

你的錯誤不是一個角度誤差,但一個JavaScript一個我的觀點。

當你這樣做: $scope.cart = sharedService.cart;

要指定的值不是引用,換句話說,它是原始值的副本,做sharedService.cart變化不會影響變量$scope.cart

在javascript中,原始變量是通過值的方式賦值的,而對象是通過引用的,所以你可以做的是將一個對象賦值爲$scope.cart

這裏是一個以它的工作爲例的plunker https://plnkr.co/edit/MKSofFcgEWMjwQaOvLsP?p=preview

+0

只需一分鐘,所以你的意思是說對象引用是內在的約束,而不是對象本身。對? – Manoj

+0

這是一個非常好的解釋關於該http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language –