[英]AngularJS: $rootScope.$watch not working as expected
I'm trying to use the $rootScope
to track favorites in my application, as they are modified I want to tell the application to update local storage to match. 我试图使用$rootScope
跟踪我的应用程序中的收藏夹,因为它们被修改了,所以我想告诉应用程序更新本地存储以使其匹配。
In my controller I am using the following function to add / delete favorites: 在我的控制器中,我正在使用以下功能来添加/删除收藏夹:
$scope.toggleFavorite = function(product) {
var item = {
id: product.id,
name: product.name
}
if (_.findWhere($rootScope.favoriteDrinks, item)) {
console.log('Rootscope contains the item: Removing');
$rootScope.favoriteDrinks = _.reject($rootScope.favoriteDrinks, function(favorite) {
return favorite.id === item.id;
});
} else {
console.log('Rootscope doesn\'t contain the item: Adding');
$rootScope.favoriteDrinks.push(item);
}
console.log($rootScope.favoriteDrinks);
}
The console.log()
produces expected results, it is updating and removing favorites as I add them throughout the application. console.log()
产生预期的结果,当我在整个应用程序中添加收藏夹时,它会更新和删除收藏夹。
For the $rootScope
I have the following code in my app.js`: 对于$rootScope
,我的app.js`中包含以下代码:
.run(['localStorageService', '$rootScope', function(localStorageService, $rootScope) {
if (!localStorageService.get('favoriteDrinks')) { localStorageService.add('favoriteDrinks', []) };
_.extend($rootScope, {
favoriteDrinks: localStorageService.get('favoriteDrinks')
});
$rootScope.$watch('favoriteDrinks', function() {
console.log('Favorite Drinks Modified');
});
}]);
So on application startup, if the localstorage keys don't exist, I create empty ones, then extend the $rootScope
to contain the favorites as retrieved from localStorage. 因此,在应用程序启动时,如果localstorage密钥不存在,则创建空密钥,然后扩展$rootScope
以包含从localStorage检索到的收藏夹。 Then I add the $watch
to the $rootScope
, however it is only firing the console.log()
when I remove something from the $rootScope
, what am I doing wrong? 然后,我将$watch
添加到$rootScope
,但是当我从$rootScope
删除某些内容时,它只会触发console.log()
,我在做什么错?
Hmm, I am not sure what _.reject(...)
do, but I think it is asynchronous. 嗯,我不确定_.reject(...)
做什么,但我认为它是异步的。
To make the $watch
statement works properly, we need to put the update statement to an asynchronous call. 为了使$watch
语句正常工作,我们需要将update语句放入异步调用。 In your case, you should you $apply or $timeout. 在您的情况下,您应该$ apply或$ timeout。
Just try: 你试一试:
$rootScope.$apply(function () {
$rootScope.favoriteDrinks.push(item);
});
or 要么
$timeout(function () {
$rootScope.favoriteDrinks.push(item);
});
Using $timeout
maybe hack-ish, but it can avoid $diggest already in process
problem. 使用$timeout
可能$diggest already in process
,但可以避免$diggest already in process
。
More info about $apply and $timeout . 有关$ apply和$ timeout的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.