Updating an array in AngularJS with Json and LocalStorage does not reflect the changes

I need to update the "color" property of an Array in a form within a View. The Array named colors consists of 5 objects that define the color of elements in another View. Since I cannot access the server, I plan to use localStorage for this task.

The form view (settings.html)

  <form name="colorform" class="row col-md-offset-1" ng-submit="update(key)">
      <div class="col-md-6">
          <div class="form-group">
              <label>Color A (Tiles)</label>
              <input name="main" ng-model="colors[0].color" class="form-control">    
          </div>
          <div class="form-group">
              <label>Color B (Blocked Tiles)</label>
              <input name="locker" ng-model="colors[1].color" class="form-control">    
          </div>
          <div class="form-group">
              <label>Color C (Path)</label>
              <input name="path" ng-model="colors[2].color" class="form-control">    
          </div>
          <div class="form-group">
              <label>Color D (Start Point)</label>
              <input name="path" ng-model="colors[3].color" class="form-control">    
          </div>
          <div class="form-group">
              <label>Color E (End Point)</label>
              <input name="path" ng-model="colors[4].color" class="form-control">    
          </div>
          <button type="submit" class="btn btn-primary">
              Update
          </button>
          <a href="#/" class="btn btn-primary">Back</a>
          <hr>
      </div>
  </form>

Excerpt from BoardController.js (for updating colors and localStorage):

//Array to be updated
$scope.colors = [
    {name: "main", color: "white"},
    {name: "locker", color: "black"},
    {name: "path", color: "yellow"}, 
    {name: "start", color: "green"},
    {name: "end", color: "blue"},
];

//localStorage

$scope.update = function (key) {
    localStorage.setItem( 'colors', angular.toJson( $scope.colors, '[]' ) );
    console.log(JSON);

    var newColors = angular.fromJson( localStorage.getItem( 'colors' ) );
    for (var i = 0; i < newColors.length; i++) {
        $scope.colors == $scope.colors;
        $scope.colors = newColors[i];

        console.log($scope.colors);
    }
}

$scope.style = function ($index) {       
    return {
        "height" : tileHeight + 'px',
        "width" : tileWidth + 'px',
        "border" : "1px solid #CCC",
        "background-color": $scope.colors[$scope.status[$index]].color,
        "float": "left"
    }
}

In main.html, using the ng-style:

<div ng-repeat="tile in getNumber(tiles) track by $index" 
     ng-click="changeToggle($index)" ng-init="initToggle($index)" 
     ng-model="status[$index]" ng-style="style($index)"></div>
</div>

The data is being stored correctly in localStorage as shown below: https://i.sstatic.net/4QUKi.jpg

However, I'm facing issues with updating the array with the localStorage information to change the colors of View main.html. What am I missing?

EDIT 1:

I made modifications to the update function as follows:

$scope.update = function (key) {
    localStorage.setItem( 'colors', angular.toJson( $scope.colors, [] ) );
    var newColors = angular.fromJson( localStorage.getItem( 'colors' ) );
    console.log(newColors);
    $scope.colors = newColors.slice(0);
    console.log($scope.colors);
}

I have commented out the loop, and now both Arrays show the same values in the console. But the update still doesn't work... Could it be an issue in the $scope.style function?

EDIT 2:

JSFiddle

EDIT 3

Question: What if I restructure it so each View has its Controller and a Service to transfer data between them? Is that a feasible solution?

Answer №1

The logic behind updating the function was flawed. Essentially, when the user clicks "Update," the localStorage data should be updated or created with new colors. However, the use of localStorage.getItem and for loop were not in the right place for this update action!

To address this issue, the successful code involved moving the localStorage.getItem and for loop outside of the $scope.update function, as shown below:

$scope.update = function () {
    localStorage.setItem( 'colors', angular.toJson( $scope.colors, '[]' ) ); 
};

var newColors = angular.fromJson( localStorage.getItem( 'colors' ) );
for (var i = 0; i < newColors.length; i++) {
    $scope.colors[i] = newColors[i];
}

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

Sending a JavaScript function as a value in a JSON object

I've been working on incorporating a word cloud with click event handler using jQCloud. To achieve this, I need to include a JavaScript function within JSON. Within C#, I have generated the dynamic JSON text: foreach (var r in result) { sbChart. ...

What is the best way to reset the selected label in a React Material AutoComplete component when the state is

I currently have a state declared as: const [searchEntryNo, setSearchEntryNo] = useState(''); In addition, there is a function set up to clear the state when needed. const handleClear = () => { setSearchEntryNo(''); }; Ne ...

Is there a way for me to track the actions of AngularJS when I interact with a link?

Within my application, there is a basic link that directs to an absolute page with its target set to blank. However, when I click on this link, the new page opens in a new window but my application screen goes blank. I am currently using Angular and tryi ...

Directive attribute causes unit test failure

Declare a directive as an Attribute: app.directive('myDirective', function() { return { restrict: 'A', replace: true, transclude: true, scope: { data: "=" }, template: ...

I am seeking assistance with my code. It is passing most of the test cases, but is failing only two without any error messages. What could

I recently started teaching myself programming, so please excuse me if my question seems a bit basic. One of the challenges on CodeCamp requires defining a function that takes an array with 2 values as input and returns the Least Common Multiple (LCM) of ...

Node.js is not accurately setting the content length. How can I resolve this issue?

I could use some assistance. Even though I have set the content-length on the response object, it doesn't seem to be working. Have I done something incorrectly? res.set({ 'Content-Type': res._data.ContentType, 'Content-Length' ...

What is the process for adding content to a JSON object?

I may have a simple question, but I'm new to backend development and I'm trying to figure out how to post in JSON format. Here is the JSON schema I am working with: email: { type: String, unique: true, lowercase: true, required ...

An issue with AngularJS where the .focus() method is ineffective within the link function

Have you ever wondered why a certain directive works in one scenario but not in another? Let's take a look at an example: angular.module('app', []) .directive('selectOnFocus', function(){ return{ restrict: ...

What steps do I need to take to create a custom image for a website?

I'm looking for a way to create a website image using just code, without the need for an actual image file or image tag. Is there a method to do this? Would I use CSS, Javascript, or HTML5 for this task? If using JavaScript to dynamically generate the ...

Display array C in descending order

My task involves creating functions to print an array and fill it with descending numbers. I successfully created the necessary functions, but encountered a problem. When I use my custom printArray() function, the output is unclear. I can't figure ou ...

Searching the JSON file by its value using Waterline

I am struggling with locating model instances based on the nested address attribute in one of my models. attributes: { address: { type: 'json' } } I have attempted various queries to find model instances located in the same city: Model ...

Having difficulty parsing key value pairs from a JSON object using JavaScript

I'm encountering difficulties with parsing a Json_encode response in a JavaScript function. The PHP script retrieves data from a database and sends the output as a Json_encode array to an HTML page. <?php include("connect.php"); try { ...

Angular - Implementing an Object Mapping Feature

Looking to dynamically generate parameter objects in Angular with a structure like this: [ password: {type: 'String', required: true, value: 'apassword'}, someRandomParam: {type: 'Integer', required: false, value:3} ] ...

What is the process for making local dynamoDB queries with dynamoose?

In order to avoid constantly connecting to Amazon Web Services as a developer, I decided to install DynamoDB on my local computer following the guidelines provided in the AWS Docs. My backend is built using node.js. For modeling Amazon's DynamoDB in ...

What is the best way to manipulate a shape in Snap.svg while ensuring the transformation does not affect its mask?

My current challenge involves transforming a rectangle with position, scale, and angle adjustments while having it masked. To illustrate my issue, I have created a fiddle file which can be accessed via this link: http://jsfiddle.net/MichaelSel/vgw3qxpg/2/ ...

Exploring asynchronous data handling in AngularJS using promises

Currently, I am working on a single page application using angularJS and encountering some difficulties in storing asynchronous data. In simple terms, I have a service that contains my data models which are returned as promises (as they can be updated asy ...

PHP WebService, exclusively containing private variables within an empty array

I'm attempting to create a PHP webservice. In the "Aluno" class, there are 2 private variables. After struggling all day with this, I finally discovered that if I change those variables to public, everything works as expected. However, if they remain ...

Transform the Nodejs server into a reusable Node module

Can a nodejs API server be transformed into a node module for use in other projects with minimal code modifications? Additional Information: The node js server contains various APIs (get, post, put). If I integrate this server as a node module within anot ...

Is it feasible to develop a functional computer interface using threejs?

Is it feasible to integrate a window into threejs that could facilitate the use of standard desktop applications (such as code editors) within the virtual scene? Please note: This is being implemented within a custom application or a node-webkit environme ...

Error encountered in Selenium WebDriver due to JavascriptException

Attempting to execute JavaScript within Selenium WebDriver has resulted in an error. The script was stored in a string variable and passed to the `executeScript()` method. Upon running the script, a `JavascriptException` occurred. Below is the code snippet ...