AngularJS watch array of objects for data change

后端 未结 3 1290
时光说笑
时光说笑 2020-11-30 05:27

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 local

相关标签:
3条回答
  • 2020-11-30 06:01

    $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

    0 讨论(0)
  • 2020-11-30 06:02

    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)

    0 讨论(0)
  • 2020-11-30 06:19

    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

    0 讨论(0)
提交回复
热议问题