$rootScope$apply()忽略变量赋值



在我的服务中,我有以下代码:

setInterval(function () {
    $rootScope.$apply(function () {
        cart.push({
            "Id": 4,
                "Name": "Some item",
                "Price": 4
        });
    });
}, 3000);

工作示例:http://jsfiddle.net/ko8edf32/7/

这是正确的:购物车更改被推送到视图中。

然而,当我为cart分配一个新值时,更改不会被推到视图中:

setInterval(function () {
    $rootScope.$apply(function () {
        var newcart = [{
            "Id": 4,
                "Name": "Some item " + Math.random(),
                "Price": 4
        }];
        cart = newcart;
    });
}, 3000);

示例:http://jsfiddle.net/ko8edf32/8/

  • 这是什么原因
  • 解决这个问题的最佳/最优雅的解决方案是什么

编辑

这是我基于以下答案构建的有效解决方案:jsfiddle.net/ko8edf32/11

我已经通过双向数据绑定将您的购物车更改为更"棱角分明"的方式。我添加了第二个控制器,向您展示了它在没有getters/setters的情况下以及通常使用一点magic 的情况下协同工作的效果

http://plnkr.co/edit/U5pUlAPJTNd9V0baSjAu?p=preview

homeApp.factory("cartService", function($rootScope) {
  var service = null
  service = {
    all: function() {
      return service.cart;
    },
    add: function(item) {
      service.total += item.Price
      service.cart.push(item);
    },
    remove: function(item) {
      service.total -= item.Price
      service.cart.splice(service.cart.indexOf(item), 1);
    },
    cartUpdated: function(newValue) {
      service.cart = newValue;
    },
    cart: [],
    total: 0
  }
  return service;
});

您必须在$scope上使用对象。

$scope.model = { cart: [] };

以下是一个工作示例:http://jsfiddle.net/56vkqygn/2/

这里有一个解释:AngularJS中范围原型/原型继承的细微差别是什么?

最新更新