Is there a way to convert a json array to a javascript array in AngularJs?

I am new to Angular and front-end development and facing a challenge that I can't seem to overcome.

After reassigning one variable to another: $scope.testarray = $scope.todos; only the 'todos' data is being displayed when using Angular bindings.

var App = angular.module('App', []);

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('todos.json')
       .then(function(res){
      $scope.todos = res.data;                
        });

  $scope.testarray = $scope.todos;
});

Here's the HTML code:

<!doctype html>
<html ng-app="App" >
<head>
  <meta charset="utf-8">
  <title>Todos $http</title>
  <link rel="stylesheet" href="style.css">
  <script>document.write("<base href=\"" + document.location + "\" />");    </script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="TodoCtrl">
  <ul>
    <li ng-repeat="todo in todos">
      {{todo.text}} - <em>{{todo.done}}</em>
    </li>
  </ul>
  this doesn't display: {{testarray}}
  </br></br>
  but this does dislay: {{todos}}
</body>
</html>

Answer №1

When looking at your code snippet

App.controller('TodoCtrl', function($scope, $http) {  
  $http.get('todos.json')
    .then(function(res){
      $scope.todos = res.data;                
    }); //.then block ends here
    $scope.testarray = $scope.todos;
});

The line $scope.testarray = $scope.todos; is located outside of the .then block. Since $http.get is an asynchronous call, this line will be executed before $scope.todos is defined.

To resolve this issue, it is recommended to move this line inside the .then block where $scope.testarray is declared.

Updated code:

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('todos.json').then(function(res){
      $scope.todos = res.data;
      $scope.testarray = $scope.todos; //Moved inside
        });
});

Feel free to ask for further assistance if needed.

Answer №2

To monitor changes in the data, I recommend using a $scope.$watch in your AngularJS application.

var App = angular.module('App', []);

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('todos.json')
       .then(function(res){
      $scope.todos = res.data;                
        });

  $scope.testarray = $scope.todos;

  $scope.$watch('todos', function(newValue, oldValue) {
      $scope.testarray = newValue;
  });
});

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

Combining two arrays filled with objects to form a collection of Objects on a Map

In my JavaScript code, I'm receiving data from a WebService that looks like this: { "fire": { "totalOccurence": 2, "statsByCustomer": [ { "idCustomer": 1, "occurence": 1 }, { "idCustomer": 2, ...

What is the reason behind postgres' error message: "operator does not exist: json ? unknown

Trying to execute this specific query against my postgres database, I encountered a challenge: select distinct offer_id from offers where listing_id = 2299392 group by offer_id having not bool_or(status in ('Rejected', 'Draft&ap ...

What steps can I take to guarantee that a directive's link function is executed prior to a controller?

Our application features a view that is loaded through a basic route setup. $routeProvider .when('/', { template: require('./views/main.tpl.html'), controller: 'mainCtrl' }) .otherwise({ re ...

HTML / CSS / JavaScript Integrated Development Environment with Real-time Preview Window

As I've been exploring different options, I've noticed a small but impactful nuance. When working with jQuery or other UI tools, I really enjoy being able to see my changes instantly. While Adobe Dreamweaver's live view port offers this func ...

The problem with legends in chart.js not displaying properly

I've been struggling to display the labels "2017" and "2018" as legends on the right side of the chart. I've tried numerous approaches but haven't found a solution yet. The purpose of showing these legends is to easily identify that each co ...

I am looking for a way to add multiple checkboxes using PHP-jQuery in conjunction with MSSQL Server. Can

I am encountering an issue while attempting to save multiple checkbox values into an MSSQL server database using PHP and jQuery. Upon executing the code, I encounter the following error: The problem seems to lie within the PHP code. How can I parse this ...

Guide for displaying and hiding an image using a button or link in Next.js

I'm a beginner with React and Next.js, and I have the following code snippet: import Link from 'next/link'; import Image from 'next/image'; async function getPokedex() { const response = await fetch(`http://localhost:3000/api/p ...

Connection lost from JS client in Twilio's Programmable Chat

My React application utilizes the Twilio Programmable Chat library for chat functionality. The setup code typically appears as follows, enclosed within a try/catch block: this.accessManager = new AccessManager(twilioToken.token); const chatClientOptio ...

Jasmine is having trouble scrolling the window using executeScript

I usually use the following command: browser.driver.executeScript('window.scrollTo(0,1600);'); However, this command is no longer working. No errors are showing in the console, making it difficult to troubleshoot. Interestingly, the same scri ...

Retrieve the parseJSON method using a string identifier

I am trying to serialize a C# const class into name-value pairs, which I need to access by their string names on the client side. For example: return $.parseJSON(constantClass).property; This approach is not working as expected. Is there any alternative ...

NPM is searching for the package.json file within the user's directory

After completing my test suite, I encountered warnings when adding the test file to the npm scripts in the local package.json. The issue was that the package.json could not be located in the user directory. npm ERR! path C:\Users\chris\pack ...

Creating a Website for Compatibility with NoScript

During my journey of building a nameplate site from the ground up for myself, I have delved into the realms of learning and establishing my online presence. The highlight of my project is a sleek tabbed site that employs AJAX and anchor navigation to seaml ...

Guide on creating an HTML5 rectangle for reuse using the Prototypal Pattern

I'm struggling to grasp Prototypal Inheritance through the use of the Prototypal pattern by creating a rectangle object and an instance of that rectangle. It seems like it should be straightforward, but I'm having trouble understanding why the Re ...

Tips for choosing elements based on the length of an array

When using an each function, I scan the DOM to find multiple elements with a specific className. Depending on the length of this ClassName, it will create an array that is either 2 or 4 elements long. I need to distinguish between these two types of elem ...

Associate an alternate attribute that is not displayed in the HTML component

Imagine there is a collection of objects like - var options = [{ id: "1", name: "option1" }, { id: "2", name: "option2" } ]; The following code snippet is used to search through the list of options and assign the selected option to anot ...

The code to trigger the button with the ID 'Button' using Document.getElementById() is not executing the associated code-behind

Having just started coding in javascript/VB.NET, I am struggling to get my Button2 onClick event to work properly. The Code-Behind Click Event for Button1 in Page.aspx.vb: Protected Sub _lnbComments_Click(ByVal sender As Object, ByVal e As System.EventAr ...

Is there a quick way to use AJAX in Rails?

By using the remote:true attribute on a form and responding from the controller with :js, Rails is instructed to run a specific javascript file. For instance, when deleting a user, you would have the User controller with the Destroy action. Then, you woul ...

Preserving and recovering shapes in OpenLayers

Background: I am brand new to OpenLayers, just hours old, so please bear with me. Basically, I have a map with some shapes drawn on it. It appears that I have multiple OpenLayer.Feature.Vector layers containing various OpenLayer.Geometry elements (like Li ...

Adding HTML content inside an iFrame at a specific cursor position in Internet Explorer

Does anyone know a method to insert HTML into an iFrame specifically for IE? I have been using execCommand insertHtml in Chrome and Firefox, but it doesn't seem to work in IE. I was able to paste HTML into a content editable div using pasteHTML, howe ...

Triggering multiple onClick events in React / Material-UI when used within a data.map() loop

My English may not be perfect. {data.sort(getSorting(order, orderBy)) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map(n => { {/*........*/} <Button onClick={this.handleLsClick}> Open Menu < ...