我正在实现购物车,并希望将数据存储在localStorage中.我想观察变量$scope.cart的变化,以便我可以更新localStorage
cart变量如下所示:
[{'name':'foo', 'id':'bar', 'amount': 1 },...]
Run Code Online (Sandbox Code Playgroud)
这是手表的代码.
$scope.updateCart = function(){
localStorageService.add('cart',JSON.stringify($scope.cart));
alert('cart updated');
};
$scope.$watch($scope.cart, $scope.updateCart(), true);
Run Code Online (Sandbox Code Playgroud)
这是用户更改模型的HTML.
<li ng-repeat="item in cart">
{{item.name}} <input type="text" ng-model="item.amount">
</li>
Run Code Online (Sandbox Code Playgroud)
使用以下代码,updateCart()永远不会触发该方法.我不确定我做错了什么.我检查$scope.cart变量确实发生了变化,但未触发更新.
Epo*_*okK 39
$watch仅在其第一个参数中计算字符串或函数参数.改变你的$watch喜好:
$scope.$watch('cart.name + cart.id + cart.amount', $scope.updateCart());
Run Code Online (Sandbox Code Playgroud)
要么
$scope.$watch('cart', $scope.updateCart, true);
Run Code Online (Sandbox Code Playgroud)
请参阅参考API
Jin*_*Jin 26
人们在监视表达式中使用变量是一个常见的错误.对于$ scope.cart,您应该使用字符串表达式'cart'.例如,
$scope.$watch('cart', function () {...}, true)
Run Code Online (Sandbox Code Playgroud)
AngularJs有一个新的监视方法,$ watchCollection.它基本上与$ watch相同,对象相等性选项设置为true以观察属性或数组项的更改.
$scope.$watchCollection('cart', function () {...});
Run Code Online (Sandbox Code Playgroud)
以下是$ watchCollection的AngularJs doc链接.http://docs.angularjs.org/api/ng/type/$rootScope.Scope.语法与$ watch基本相同,除了它没有第3个参数(对象相等性检查)