简体   繁体   中英

AngularJS localstorage for a factory

I am a newbie to IonicFrameWork and was following their "starter tab" template and made a few modifications to "delete" and "bookmark" items from a factory.

My books.js which contains the factory looks as follow:

.factory('Books', function() {

  // books data
  var books = [{
    id: 0,
    title: 'Sample Title',
    author: 'Sample Author',
    category: 'Horor, Fiction',
    cover: '/cover.jpeg',
    details: 'some details about the book',
    chapters: [
      {
        id : 1,
        name: 'Chapter 1',
        filename: 'chapter1.html',
      },
      {
        id : 2,
        name: 'Chapter 2',
        filename: 'Chapter2.html',
      }
    ]
  }
  .....  
  return {
    all: function() {
      return books;
    },
    // remove a book from the list
    remove: function(book) {
      books.splice(books.indexOf(book), 1);
    },

and my controllers.js looks like this:

....
.controller('DashCtrl', function($scope, Books) {

  $scope.books = Books.all();
  $scope.remove = function(book) {
    Books.remove(book);
  };
})
.controller('singlebookCtrl', function($scope, $stateParams, Books){
  $scope.book = Books.get($stateParams.bookId);
  $scope.toggleIcon = function ($evemt, iconName, book){
  var buttonClasses = $event.currentTarget.className;
  // add the book to favorite
  if (....){
      book.isFavorite = true;
  }
  // remove the book from favorite 
  else {
      book.isFavorite = false;
  }
  ....

when I exit the app and open it again, the deleted item is back and favorite items are gone.

When searching for a solution , I came across this article which states I should use window.localstorage . But not sure how I should apply this method for a factory.

I personnaly prefer using ngStorage that makes it very simple and straight forward to use localStorage & sessionStorage .

For example, after injecting the dependency in your controller you can:

Set a variable :

$scope.favList = [1, 4, ...]
$scope.jsonList = { ... }
$localStorage.favLists = $scope.favList;
$localStorage.jsonList = $scope.jsonList;

Access a variable, Simply access to localStorage value :

var favList = $localStorage.favLists;

For all intents and purposes you can treat Local Storage just as if it were a key/value store, like a javascript object. So if you want to save a value in local storage, just do it like the following.

window.localStorage["bookOne"] = "STRING HERE"

Or if you want to save a javascript object:

window.localStorage["bookOne"] = JSON.stringify({a:b})

And it should persist between page reloads.

The real issue here is that in your code, you are setting books on each load with var books = ... . Every time you reload the application it will re-apply books and favourites will be lost. So beyond just saving it to window.localStorage you will also have to read from local storage and assign it to your books and favourites variables when your app loads in order to see the changes that were previously made.

You can simply do it with angular-local-storage module, here's some example based on your problem.

angular.module('app', ['LocalStorageModule'])
  .factory('Books', function(localStorageService) {
    // favorites list(books id)
    var favList = [1, 2, 3, ...];
    // ....
    return {
      remove: function(id) {
        favList.splice(favList.indexOf(id), 1);
        // sync with localStorage
        localStorageService.set(favorites, favList);
      },
      // ....
    }
  });

Note that you can simply use angular-local-storage#bind and bind specific scope-key to this service that automatically do this synchronisation for you. for example:

// Inside your controller
$scope.favList = [1, 4, ...]
// returns a deregistration function for this listener.
$scope.unbind = localStorageService.bind($scope, 'favList');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM