AngularJS factory with local storage functionality

As a newcomer to IonicFrameWork, I decided to try out their "starter tab" template and made some tweaks to the functionality of deleting and bookmarking items from a factory.

In my books.js file where the factory is defined, here's a snippet of what it looks like:

.factory('Books', function() {

  // books data
  var books = [{
    id: 0,
    title: 'Sample Title',
    author: 'Sample Author',
    category: 'Horror, 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);
    },

Then, in my controllers.js, I have the following setup:

....
.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 ($event, 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;
  }
  ....

Here's the issue I encountered - when I close the app and open it again, the deleted item reappears and the favorited items are no longer saved.

After researching for a solution, I stumbled upon this informative article suggesting the use of window.localstorage for data persistence. However, I'm unsure how to implement this method within a factory structure.

Answer №1

In my opinion, I find ngStorage to be the most convenient option when it comes to utilizing

localStorage & sessionStorage
.

For instance, once you have added the dependency in your controller, you can easily:

Assign a value :

$scope.favoriteNumbers = [1, 4, ...]
$scope.dataList = { ... }
$localStorage.favorites = $scope.favoriteNumbers;
$localStorage.dataList = $scope.dataList;

Retrieve a value, Simply retrieve the localStorage data :

var favoriteNumbers = $localStorage.favorites;

Answer №2

When working with Local Storage, you can think of it as a key/value store similar to a JavaScript object. To save a value in local storage, simply use the following code snippet.

window.localStorage["bookOne"] = "VALUE GOES HERE"

If you need to store a JavaScript object:

window.localStorage["bookOne"] = JSON.stringify({key: value})

Your data should remain intact even after reloading the page.

Answer №3

The main concern lies in the code you have written, where the variable books is set on each load using var books = .... This means that every time the application is reloaded, the books data is refreshed and any favorites selections will be lost. To address this issue, in addition to saving data to window.localStorage, you will also need to retrieve the saved data from local storage and assign it to both the books and favorites variables when your application loads. Only then will you be able to retain the changes previously made.

Answer №4

If you're looking to tackle this issue, utilizing the angular-local-storage module is your best bet. Below is an example tailored to address your specific challenge:

angular.module('app', ['LocalStorageModule'])
  .factory('Books', function(localStorageService) {
    // List of favorite books (by ID)
    var favList = [1, 2, 3, ...];
    // ....
    return {
      remove: function(id) {
        favList.splice(favList.indexOf(id), 1);
        // Update localStorage
        localStorageService.set(favorites, favList);
      },
      // ....
    }
  });

Keep in mind, you have the option to leverage angular-local-storage#bind and connect a specific scope-key to this service for automatic synchronization. Here's an example:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for effectively creating a fresh array of objects by extracting distinct values from arrays of child elements within a collection of parent objects

We have a requirement to extract data from objects structured like this: [ { "first": { "children" : [{ "name": "abc", "detail":"123"}, { "name": "def", "detail":"456"} ] }}, { "second": { "children" : [{ ...

Valums file-uploader: Restricting file uploads based on user's credit score

Currently utilizing the amazing file uploader by Valums, which can be found at https://github.com/valums/file-uploader One feature I am looking to incorporate is a limit based on the user's account balance. The initial image upload is free, so users ...

Add HTML code into a contenteditable element and then include additional text following the inserted HTML

I'm working with a contenteditable div and a button that inserts a simple span. <button id="insert-span">Insert</button> <div id="edit-box" contenteditable="true"></div> <script> $('#insert-span').on(' ...

AngularJS: Modifying model via directive

I am having trouble with updating the model after using a drag and drop directive. Although the drag and drop functionality is working fine, when I drop some text into the textarea, the displayed text appears correctly but the model is not being updated. ...

Error: The term "Worker" is undefined in a new Nextjs project

I'm currently looking into an issue where I am attempting to import a webpacked javascript file into a NextJS project that utilizes Worker, but I keep encountering the error message ReferenceError: Worker is not defined. I've simplified it down t ...

Encountering a "map is not a function" error in REACT following the use of the push method

After pushing an element to an array in a function (event), I encountered the following error: handleAddList(s) { this.setState({lists :this.state.lists.push(s)}); console.log(this.state.lists); } The error message says "lists.map is not a function. ...

Ways to retrieve the initial key object received through an AJAX request

I have a form with three dynamic dropdowns. The second dropdown depends on the first one, and the third dropdown depends on the second one. Therefore, selecting an option in the first dropdown will automatically populate the next two dropdowns. Below is t ...

remove an element from a nested array using MongoDB

Greetings everyone! I am currently working on a materials document that contains arrays of articles, each article having an array of details. Here is a snippet from my collection data: { "_id": "62f2404b42556d62e2939466", "code&quo ...

Tips for Using Threejs Loaders in a React App

Greetings and thank you for taking the time to read my question. ...

JQuery UI autocomplete vanishes instantly without any warning

I am encountering an issue with JQuery UI's autocomplete feature where the dropdown results do not stay visible. While debugging, I noticed that the list briefly appears before disappearing. Below is my code snippet: HTML: <input type="text" plac ...

"Customizable rectangular container with jagged edges created with Scalable Vector Graphics

Currently, I am undertaking a small project that involves creating a box with rough edges around some text. To achieve this effect, I am utilizing an SVG with unique edges similar to the design found at this link: (except mine is in SVG format). My goal ...

Show notifications after being redirected to a new page

My goal is to submit a form and have the page redirected to a different URL upon submission. Currently, everything works as expected, but there is an issue with the timing of the toast message. The toast message appears immediately after the user clicks th ...

JavaScript objects and AJAX versus ASP MVC3 Model: A comparison of client-side and server

As someone who is still learning about MVC, I find myself a bit unsure about the best way to integrate MVC models with JavaScript objects and AJAX. For instance, in one of my applications, I have a calendar that displays user events stored in a database. ...

Error: Module instantiation failed due to an uncaught error

Oops! Encountered an Uncaught Error: [$injector:modulerr] for failing to create the module myApp. The error message reads: Error: [$injector:nomod] Module 'myApp' cannot be found! This could be due to a misspelled module name or forgetting to loa ...

The jQuery Multiselect filter contradicts the functionality of single select feature

http://jsfiddle.net/rH2K6/ <-- The Single Select feature is functioning correctly in this example. $("select").multiselect({ multiple: false, click: function(event, ui){ } http://jsfiddle.net/d3CLM/ <-- The Single Select breaks down in this sc ...

What is the best way to deselect the first radio button while selecting the second one, and vice versa, when there are two separate radio groups?

I am looking to achieve a functionality where if the first radio button is selected, I should receive the value true and the second radio button should be unselected with the value false. Similarly, if the second radio button is selected, I should receive ...

What is the best way to use AJAX to send a downloadable file in WordPress?

Currently working on developing a WordPress plugin and could use some assistance ...

Retrieving CSS properties of an element using JavaScript

How can I efficiently retrieve all CSS rules associated with a specific element using JavaScript? I am not seeking a particular solution, just looking to capture all CSS rules for the given element. For example, consider the following HTML code: <div ...

Typescript encountering onClick function error during the build process

My current challenge involves creating a submit function for a button in my application. However, when I attempt to build the project, I encounter a typing error that is perplexing me. Despite trying various methods, I am unable to decipher how to resolve ...

What is the best way to dynamically load a personalized JavaScript file for individual users depending on their PHP login credentials?

Currently, I am conducting a web-based experiment in which students log into a website to take practice tests for a class. Initially, the students land on a login page that includes the following code: include_once("core/config.php"); include_once("core/ ...