Updating AngularJS ng-repeat when changes are made to LocalStorage with the use of store.js may not reflect immediately

One of the functionalities I want to implement is displaying a list of items (subject names) that are stored in a LocalStorage element. The code snippet in my view is structured as follows:

<div class="list">
  <a class="item" href="#" ng-repeat="subject in subjects">
    {{subject.name}}
  </a>
</div>

This is how my controller is set up:

.controller('SubjectCtrl', function ( $scope ) {

  $scope.subjects = store.get('subjects');

  $scope.submit = function() {
    if (store.get('subjects') != null) {
      var existing = store.get('subjects')
      var subject = [ { name: $scope.form.name, weighting: $scope.form.weighting, grades: [] } ]
      subject.add(existing)
      store.set('subjects', subject)
    }
    else {
      var subject = [ { name: $scope.form.name, weighting: $scope.form.weighting, grades: [] } ]
      store.set('subjects', subject)
    }
  };
})

The $scope.subjects variable fetches data from LocalStorage using Store.js (https://github.com/marcuswestin/store.js, a Plugin that simplifies LocalStorage access) and passes it to the view.

Upon submitting a form to add a new subject, the following code block executes. The form comprises 'name' and 'weighting' inputs. If there are existing subjects in the 'subjects' LocalStorage object, the new subject gets appended to the array, updating the LocalStorage. If not, a new LocalStorage object named 'subjects' is created, and the new subject is added.

Despite functioning correctly, I face an issue where Angular fails to update the view when a new subject is added to the array in LocalStorage, necessitating a manual page reload to reflect the changes.

After some investigation, I discovered this might be due to updating the LocalStorage object outside of AngularJS’s scope. As a novice in Angular, I seek guidance on the best approach to alert Angular about object modifications promptly.

Any assistance would be highly appreciated!

-- UPDATE --

I've transitioned from store.js (incompatible with Angular) to ngStorage (https://github.com/gsklee/ngStorage). To potentially aid others, here's my revised controller code employing ngStorage:

.controller('SubjectCtrl', function ( $scope, $localStorage ) {
  $scope.$localStorage = $localStorage.$default({
    subjects: []
  });

  $scope.subjects = $localStorage.subjects;

  $scope.submit = function() {
    $localStorage.subjects.push({ name: $scope.form.name, weighting:  $scope.form.weighting, grades: [] });
  };
})

Answer №1

There are a couple of areas in your code that could use some enhancement -- the most crucial being that you fail to notify $scope about the modification. Give this solution a try and inform me if it makes a difference:

.controller('SubjectCtrl', function ( $scope ) {
    $scope.subjects = store.get('subjects');
    if($scope.subjects == null) {
        $scope.subjects = [];
    }

    $scope.submit = function() {
        $scope.subjects.push({ name: $scope.form.name, weighting: $scope.form.weighting, grades: [] });
        store.set('subjects', $scope.subjects)
    };
})

-- UPDATE --

The resolution OP discovered is detailed in the revised question posted above.

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

What is the best way to transform the pages extracted through the Notion API into slugs?

I'm new to Next.js and Notion API, and I want to create a blog site on my personal website using the Notion API. While I can easily pull the posts, I am facing a challenge in slugifying the endpoint IDs with post titles. When attempting this based on ...

Limit file selection to images using MUI File Input

I am currently using MUI File Input in React for a file input element. The code I have works well, but I would like to restrict this file input to only accept images. How can I achieve this? Here is what I have done so far: const [locationImg, setLoc ...

Changing the className of buttons based on user interaction

I'm looking to create a function in React JS that changes the button's color when clicked. Specifically, I want the color of the button to change upon clicking. I have attempted to achieve this using the following code: {"classname" i ...

Tips on effectively utilizing a value that has been modified by useEffect

Here is my current code: const issues = ['x','y','z']; let allIssueStatus; let selectedIssueStatus = ''; useEffect(() => { const fetchIssueStatus = async() => { const response = await fetch(&ap ...

Determining the emptiness of an array in Postman using node.js

When I receive a response, it is in the following format: { "test1": [], "test2": [], "test3": [], "test4": null, "test5": [] } This is the response that I get after making a request. I need to verify whether test1 is empty or not. ...

Create a dynamic AppBar Toolbar in React Admin that changes based on the current page

Recently delving into the world of React, I've been facing some challenges when it comes to loading IconButtons onto the toolBar of an AppBar (from Material UI). For instance, I'm looking to have two specific IconButtons displayed on pageA and d ...

Error in Node.js: Using `import` token incorrectly

I am having trouble figuring out what the issue is. Node v5.6.0 NPM v3.10.6 This is the code snippet: function (exports, require, module, __filename, __dirname) { import express from 'express' }; The error message reads: SyntaxError: Une ...

Updating a React application that was originally built using Node v16 to the latest version of Node, v18,

I have a React project that was originally built on node v16 and now I need to update it to node v18. How can I do this quickly without changing dependencies or causing other issues? When I tried installing the dependencies in node 18, everything seemed f ...

The node experiences a crash when the redis-server goes offline

Struggling with a persistent issue here. Despite reading numerous documents and posts from others on the same topic, I can't seem to find a solution to prevent this problem. I am intentionally shutting down the redis server to avoid potential disaster ...

What is the most effective way to display a success notification?

After updating the data in my application, I want to display a success message. Although the Success function is functioning correctly, the message itself is not appearing. When I click on the save() button, a small alert box pops up but the message fails ...

How can I make tooltipster display tooltips properly?

I have been struggling to customize tooltips using a library called tooltipster. Here is what I currently have: Head of index.html: <head> <!--TOOLTIP CSS--> <link rel="stylesheet" type="type/css" href="node_modules/tooltipster-master ...

How to incorporate a custom JavaScript file into an Angular 7 application

Suppose there is a JavaScript file named mylib.js in an angular 7 application, located at assets/mylib.js: mylib = function(){ return { hi: function() { alert('hi'); } }; }(); If I want to be able to call mylib.hi() in my hero-f ...

Sharing data within angularJS applications can provide numerous benefits and increase

As a beginner in angularJS, I find myself still grappling with the concept of data sharing among various components like controllers, directives, and factories. It seems there are multiple methods available for facilitating communication between them -- ...

Why does modifying a variable within the fetch URL result in undefined

I currently have a server running on the URL http://localhost:3000/. Within my JavaScript code, I have defined a variable called productCode with the value 'example-code55'. let productCode = 'example-code55'; const fetchData = async ...

Setting up Angularjs on your computer with the help of bower

In my home country, certain social networking websites and other online platforms are restricted. For instance, I am unable to access sites like meteor.com, codecademy.com, bower.herokuapp.com, and more. When attempting to install packages by running the & ...

Discovering the value of an item when the editItem function is triggered in jsGrid

Within my jsGrid setup, I have invoked the editItem function in this manner: editItem: function(item) { var $row = this.rowByItem(item); if ($row.length) { console.log('$row: '+JSON ...

Efficiently select multiple classes in Material UI with just one target

I'm currently working with Material UI and I want to update the color of my icon class when the active class is triggered by react-router-dom's NavLink Here is my code: import React from "react"; import { makeStyles } from "@mater ...

I'm having trouble with my react-big-calendar not updating when I switch between day, month, or week views -

Why won't my calendar change to the week view when I click on that section? https://i.stack.imgur.com/gh2aO.png In the screenshot above, my default view is set to month, but when I attempt to switch to week, it only highlights the option without cha ...

Problem with Angular 2 Typings Paths in Typescript

Currently, I am in the process of learning how to create a Gulp build process with Angular 2 and Typescript. Following the Quick Start guide has allowed me to get everything up and running smoothly. However, I have decided to experiment with different fold ...

Identifying a failed Ajax Request in JavaScript

How can I check if an Ajax request failed to load a file? Here is the code I'm currently using: var pro = undefined; var xmlhttp; if (window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTT ...