AngularJS watch array of objects for data change

一曲冷凌霜 提交于 2019-11-26 12:43:23

问题


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

The cart variable looks like this:

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

This is the code for the watch.

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

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

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>

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.


回答1:


$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());

OR

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

See reference API




回答2:


It's a common mistake that people use variable in the watch expression. for $scope.cart, you should use a string expression 'cart' instead. For example,

$scope.$watch('cart', function () {...}, true)

AngularJs has a new watch method, $watchCollection. It is basically the same as $watch with the object equality option set to true to watch the change in a property or an array item.

$scope.$watchCollection('cart', function () {...});

Here is the link to AngularJs doc for $watchCollection. http://docs.angularjs.org/api/ng/type/$rootScope.Scope. The syntax is basically the same as $watch except it does not have the 3rd param (object equality check)




回答3:


try to change

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

to

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

$watch only evaluate string or function parameter in its first argument



来源:https://stackoverflow.com/questions/17417597/angularjs-watch-array-of-objects-for-data-change

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!