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

Asynchronous JavaScript function within a loop fails to refresh the document object model (DOM) despite

I have been working on a function that utilizes ajax to retrieve instructions from a backend server while the page is loading. The ajax code I've written retrieves the instructions based on the number provided and displays them using the response.setT ...

Designing a photo frame slider for a unique touch

My skills in javascript and jQuery are limited, but I am looking to create a customizable slider. While exploring options like Flexslider (), I found it challenging to meet the following specifications: Eliminate color gaps between thumbnails Enable thu ...

Tips for effectively utilizing JavaScript regex to precisely match a string before triggering the submit button

I have a form in Angular with a text input field that requires the entry of lowercase letters separated by commas, like this: c, d, e, g, a, f etc... Currently, the submit button activates as soon as any part of the input matches the required format, allo ...

React - updates to server values do not display in DOM right away

When I work from the client side, I have a modal in my HomeComponent that allows me to select an element. My goal is to then display that selected element within the same HomeComponent (in the productosEnVenta function). The element chosen in the modal is ...

Executing a series of tests using Postman

Is running multiple requests in a postman script feasible? I have an endpoint: http://localhost/gadgets/{id}/buy This endpoint sets a flag in a gadget object/entry based on its id. With hundreds of gadgets, can I use a shared file of ids to create and run ...

Karma presents a challenge when it comes to structuring the testing of requests

Below is the code snippet of the controller that I am currently testing: angular .module('mean-starter') .controller('AdminController', AdminController); function AdminController(User, Auth, $state) { var vm = this; User . ...

"Creating varying lengths of time with useSpring: A Step-by-Step Guide

Is there a way for my component to have an animation that fully displays in 0.3s when my mouse enters, but disappears in 0.1s when my mouse leaves? Currently, with useSpring, I can only define one duration for both scenarios. How can I set different dura ...

When the phone locks, Socket.io experiences a disconnection

setInterval(function(){ socket.emit("stayalive", { "room": room }); }, 5000); I have developed a simple browser application with an interval function that is currently running on my phone. I am using Chrome on my Nexus 4 for debugging purposes. However, ...

Leverage the package.json script without relying on any yarn/npm commands

Can scripts commands be executed within the package.json file without needing to include yarn or npm? For example: "scripts": { "get": "node index.js" } Currently, in order to run this script I have to use yarn get [ar ...

Can a single value be stored in a table using a radio button?

I have created an HTML table that is dynamically generated from a database. I am using a for loop to populate the table. However, I am facing an issue where each radio button in the table holds only one value. What I actually want is for each row to have ...

Ways to verify if a component triggers an event in VueJS

I am currently working with two components within my application. The Child component emits an 'input' event whenever its value is changed, and the Parent component utilizes v-model to receive this updated value. In order to ensure that the funct ...

I'm having issues with my flipclock moving too quickly and skipping over certain numbers. Any suggestions on how to resolve this issue?

My flip clock script is behaving oddly, moving too quickly and skipping over even numbers. I've been playing around with the code, and it seems like there's a problem when I use the callbacks function. var clock = $('#clock3').FlipClo ...

JavaScript is throwing an error related to 'typeError' even after explicitly converting to a string

Dealing with JS bugs can be quite frustrating for me. The code snippet below is giving me trouble, as it creates a string containing session data and date information to push into an array: var _writes = String(req.session.subscriber + ":" + req.session.po ...

Obtain an array of images from the Google Places API through a nearby search functionality

Utilizing the Google Places API within a JSP to retrieve JSON data in JavaScript has been successful, except for one aspect - the photos. Despite using the nearbySearch function, the PlacePhoto object is not populating as expected. Here is the nearbySearc ...

Issue with using bind(this) in ajax success function was encountered

In my development process, I utilize both react and jQuery. Below is a snippet of the code in question. Prior to mounting the react component, an ajax request is made to determine if the user is logged in. The intention is for the state to be set when a ...

Error caused by live data dynamic update on Highstock chart: Cannot access property 'info' of undefined

Utilizing Laravel, I was able to create Highcharts by consuming data from a Rest API link (Spring app) at . The data is currently displayed statically, but I want to dynamically visualize it on charts. I attempted to follow this example on Fiddle and inte ...

Adding and removing form fields in a table dynamically using AngularJS

I need to dynamically add multiple form fields when a button is pressed, and I want all the fields to be displayed in a table format (each field should have its own space in a <td>field</td> structure). Currently, I am facing an issue where if ...

Unbounded AngularJS 1.x looping of Ag-grid's server-side row model for retrieving infinite rows

I am obtaining a set of rows from the server, along with the lastRowIndex (which is currently at -1, indicating that there are more records available than what is being displayed). The column definition has been created and I can see the column headers in ...

Leveraging depends alongside max for jQuery validation

Trying to implement a conditional max value on a field using jQuery validation, but encountering issues. Even though I've utilized the depends function, it seems like the validate function is not functioning as expected. The code block appears correc ...

Load images in advance using this script

Using a script to load images on two websites, the image is placed inside a div with the ID div-to-load-external-image Encountering an issue where PageSpeed Insights advises to preload these images, seeking guidance... Any assistance will be appreciated. ...