角度绑定不会更新

时间:2013-01-30 04:23:06

标签: javascript angularjs

我正在使用angularjs为电子商务网站制作前端,到目前为止我遇到的唯一问题与购物车实施有关。我有一个提供Cart功能的服务,该功能包含来自购物车的addchangeremove项目的原型方法。这是它的一个非常基本的版本(它包含在服务声明中):

var Cart = function(){
  this.items = [];
  this.total_price = 0;
  this.item_count = 0;
}

Cart.prototype.getItems = function(){ return this.items }
Cart.prototype.getTotal = function(){ return this.total_price }

// Add a product to the cart
Cart.prototype.add = function(product, variant, qty){
  // Check if the item is already in the card and add to the quantity
  // or create the line item and add it to the list
  this.items.push(item)

  // Update totals
  this.total_price += product.price * qty;
  this.item_count += qty;
  console.log('Added product. total:', this.getTotal())
}

// Modify a product in the cart
Cart.prototype.change = function(product, variant, qty){
  // Find the item or error

  existingItem.quantity += qty;
  existingItem.line_price += existingItem.price * qty;
}

// Remove an item from the cart
Cart.prototype.remove = function(item){
  var index = this.items.indexOf(item);
  if (index !== -1) {
    this.total_price -= item.line_price;
    this.item_count -= item.quantity;
    this.items.splice(index, 1);
  }
  console.log('Removed line item. total:', this.getTotal())
}

return new Cart;

这个代码在直接使用时似乎运行良好,但在控制器中绑定它时会出现一个奇怪的问题。这是推车控制器:

app.controller('CartCtrl', [
  '$scope',
  'Cart',
  function($scope, Cart) {
    $scope.items = Cart.getItems();
    $scope.total = Cart.getTotal();
    $scope.delete = function(item){ Cart.remove(item) };
  }
]);

当我将产品添加到购物车时,$scope.items将更新并显示在ng-repeat ed列表中,但$scope.total绑定不执行任何操作。我知道它实际上正在更新,因为我在调试时已将console.log放在任何地方。我还尝试在更新总数后调用$rootScope.$apply(),但它只是错误,因为它已经在运行。

有没有人有任何想法?谢谢你的帮助!

1 个答案:

答案 0 :(得分:3)

看看这是你的问题......这一行

$scope.total = Cart.getTotal();

在$ scope上创建一个total属性,并且因为getTotal()返回一个原始值,所以$ scope.total设置为0.这里没有绑定,所以$ scope.total在Cart的时候不会更新total_price更改。

($ scope.items将在Cart的项目更改时更新,因为$ scope.items被分配了对items数组的引用。)

相关问题