AngularJS watch array of objects for data change

☆樱花仙子☆ 提交于 2019-11-27 04:11:33
EpokK

$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

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)

Roger Jin

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

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