我是新角度和仍與基礎掙扎。價值未更新
我在我的菜單中有一個購物車圖標,第一次加載時預設值爲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>
你可以發佈購物車的東西的HTML端嗎? –
可以幫助嗎? http://stackoverflow.com/questions/15800454/angularjs-the-correct-way-of-binding-to-a-service-properties – Dario
@JohnMc,請看現在 – Manoj