数据变更对象AngularJS手表阵列 [英] AngularJS watch array of objects for data change

查看:94
本文介绍了数据变更对象AngularJS手表阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现一个购物车,并要存储localStorage的数据。
我想观察的变量 $ scope.cart 变革,这样我可以更新localStorage的

I'm implementing a shopping cart and want to store the data in localStorage. I want to watch the variable $scope.cart for change so that I can update the localStorage

cart变量是这样的:

The cart variable looks like this:

[{'name':'foo', 'id':'bar', 'amount': 1 },...]

这是code手表。

$scope.updateCart = function(){
    localStorageService.add('cart',JSON.stringify($scope.cart));
    alert('cart updated');
};

$scope.$watch($scope.cart, $scope.updateCart(), true);

这是用户更改模型的HTML。

This is the HTML where the user changes the model.

<li ng-repeat="item in cart">
  {{item.name}} <input type="text" ng-model="item.amount">
</li>

通过以​​下code时, updateCart()方法不会被触发。我不知道我在做什么错。我检查 $ scope.cart 变量的确发生了变化,但不会触发更新。

With the following code, the updateCart() method is never triggered. I'm not sure what I'm doing wrong. I check that the $scope.cart variable did change, but the update was not triggered.

推荐答案

$观看只评估它的第一个参数字符串或函数参数。更改 $观看是这样的:

$watch only evaluate string or function parameter in its first argument. Change your $watch like this :

$scope.$watch('cart.name + cart.id + cart.amount', $scope.updateCart());

$scope.$watch('cart', $scope.updateCart, true);

请参阅参考API

这篇关于数据变更对象AngularJS手表阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆