值未更新

11 浏览
0 Comments

值未更新

我对Angular还不熟悉,仍在努力理解基础知识。

在我的菜单中有一个购物车图标,初始加载时值为0。

在产品列表中,每个产品都有一个“AddToCart”按钮。

所以我想要的是 -

每当我点击“AddToCart”按钮时,我想要更新购物车的值。然而,购物车的初始值是由Angular设置的,但我无法进一步更新它。

以下是代码 -

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;

}

页面初始加载时,它会在视图中设置购物车的值 -

{{cart}}

当我在另一个控制器中更改值并设置它时 -

function ProductListController($scope, sharedService) {

$scope.addItemToCart = function (product) {

sharedService.setCartValue(product);

}

}

它不会更新购物车的值,它仍然是0。

我该如何在Angular中更新值?

编辑

这是我调用添加按钮的视图 -

{{product.salePrice}}

Add To Cart

0
0 Comments

这个问题的出现原因是在JavaScript中对值进行复制而不是引用。当执行$scope.cart = sharedService.cart;时,你实际上是将值复制给了$scope.cart,而不是引用。换句话说,$scope.cart只是原始值的一个副本,对sharedService.cart的更改不会影响到$scope.cart变量。

在JavaScript中,原始变量是通过值进行赋值的,而对象是通过引用进行赋值的。所以你可以将一个对象赋值给$scope.cart

这里有一个示例的plunker,展示了它的工作原理:https://plnkr.co/edit/MKSofFcgEWMjwQaOvLsP?p=preview

等一下,你的意思是内部绑定的是对象引用,而不是对象本身。对吗?

这里有一个非常好的解释:stackoverflow.com/questions/518000/…

0