2

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?

Neil
  • 2,509
  • 7
  • 32
  • 47

1 Answers1

0

Hmm, I am not sure what _.reject(...) do, but I think it is asynchronous.

To make the $watch statement works properly, we need to put the update statement to an asynchronous call. In your case, you should you $apply or $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.

More info about $apply and $timeout.

Community
  • 1
  • 1
long.luc
  • 1,191
  • 1
  • 10
  • 30