数据变更对象AngularJS手表阵列 [英] AngularJS watch array of objects for data change
问题描述
我实现一个购物车,并要存储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屋!