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.
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.
For the $rootScope
I have the following code in my 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. 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?