mercredi 1 juillet 2015

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.

Aucun commentaire:

Enregistrer un commentaire