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