javascript - AngularJS localstorage for a factory -
i newbie ionicframework , following "starter tab" template , made few modifications "delete" , "bookmark" items factory.
my books.js
contains factory looks 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 book', chapters: [ { id : 1, name: 'chapter 1', filename: 'chapter1.html', }, { id : 2, name: 'chapter 2', filename: 'chapter2.html', } ] } ..... return { all: function() { return books; }, // remove book list remove: function(book) { books.splice(books.indexof(book), 1); },
and controllers.js
looks 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 book favorite if (....){ book.isfavorite = true; } // remove book favorite else { book.isfavorite = false; } ....
when exit app , open again, deleted item , favorite items gone.
when searching solution , came across this article states should use window.localstorage
. not sure how should apply method factory.
i personnaly prefer using ngstorage makes simple , straight forward use localstorage & sessionstorage
.
for example, after injecting dependency in controller can:
set variable :
$scope.favlist = [1, 4, ...] $scope.jsonlist = { ... } $localstorage.favlists = $scope.favlist; $localstorage.jsonlist = $scope.jsonlist;
access variable, access localstorage value :
var favlist = $localstorage.favlists;
Comments
Post a Comment