gsklee / ngStorage

localStorage and sessionStorage done right for AngularJS.
MIT License
2.33k stars 461 forks source link

Error: undefined is not an object (evaluating '$localStorage.$default') #221

Closed kgudipati closed 8 years ago

kgudipati commented 8 years ago

Here is my Storage Factory: angular.module('starter.services')

.factory ('ShoppingListService', [function ($localStorage) {

// initialize our shopping list in our local storage
$localStorage = $localStorage.$default({ ***ERROR HERE***
  shoppinglist: []
});

// get all the items in the user's shopping list in our local storage
var _getAll = function () {
    return $localStorage.shoppinglist;
};

// add an item to the users shopping list
var _add = function (item) {
    console.log(item);
    $localStorage.shoppinglist.push(item);
}

// remove an item from the user's shopping list
var _remove = function (item) {
    console.log(item);
    $localStorage.shoppinglist.splice($localStorage.shoppinglist.indexOf(item), 1);
}

// check whether an item is in the user's shopping list
var _isInShoppingList = function(item) {
    return $localStorage.shoppinglist.indexOf(item) > -1;
}

return {
    getAll: _getAll,
    add: _add,
    remove: _remove,
    isInShoppingList : _isInShoppingList
};

}]);

When my controller tries to call the Service and get the shopping list: $scope.shopping_list = ShoppingListService.getAll();

I'm getting the error: Error: undefined is not an object (evaluating '$localStorage.$default')

I injected the module in my app.js and properly inject my service to my controller, but I don't seem to understand what the problem is.

egilkh commented 8 years ago

Can you try changing

.factory ('ShoppingListService', [function ($localStorage) {

to

.factory ('ShoppingListService', ['$localStorage', function ($localStorage) {

Also be sure to have included ngStorage as a dependency for you module/app.

egilkh commented 8 years ago

No response from user.

4xle commented 7 years ago

FWIW I had a similar issue which ['$localStorage', function ($localStorage) { solved. Might be because I'm new to Angular but it wasn't immediately obvious to me what the issue was.