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

Executing a callback function in Swift using JavaScriptCore

Struggling to figure out how to call a Javascript Function with a callback from Swift, but it's not working as expected. Here's what I have: Javascript: global.calculateWithCb = function(temp,cb){ cb(5 * temp) } global.calculate = functi ...

Unique validation feature implemented in Parsley.js runs through validation loop twice

I've spent the entire afternoon trying to figure this out, but I just can't seem to debug it. The issue arises when I do a hard refresh of the page and my custom async validator runs twice, yet only sends one request to the server. window.Parsle ...

Retrieve items within an array of objects in MongoDB using an array of IDs (using the $in operator in aggregation)

In my MongoDB database, I have a collection of stores [ { "_id" : ObjectId("6043adb043707c034d5363b7"), "shopId" : "shopid1", "appId" : "777", "shopItems" : [ { ...

Displaying client-side filtered rows in a jqGrid with postData filter upon initial loading

Our website includes a jqGrid that initially retrieves its rows using the built-in ajax fetch feature, returning a json object. We then apply filtering and searching on the client side by creating custom functions to generate postData filters. However, we ...

Incorporate a dynamic value into a JSON string within C#

Struggling to pass C# variables into this string. Feeling lost on how to accomplish it. This is the original string without any variables: string data = @"{ ""fields"": { ""project"": { "& ...

Puppeteer: Navigate to a specific page number

I'm encountering an issue with a table and page numbers as links, such as: 1, 2, 3, 4 etc… -> each number is a link. Attempted to create a loop to click on different page numbers. On the first iteration, I can reach page 2. However, on the secon ...

webdriverio encountering difficulties selecting element for interaction

Trying to interact with a button using the webdriverio/mocha framework, the code snippet is as follows: describe ('Mytest', function () { beforeEach(function() { browser.url('/'); }) it ('should click', function () { ...

Switch up a font style using JavaScript to apply a Google font effect

I am attempting to implement a discreet hidden button on a website that triggers a unique Google font effect for all of the h1 elements displayed on the page. However, I am uncertain about the process and unsure if it is achievable. Below is the code snipp ...

What is the best way to implement pagination for JSON data in PHP?

My webservice allows users to send URL parameters such as 'start' and 'limit', enabling them to specify the number of JSON objects displayed per page and their desired starting page. Below is the PHP code I've implemented for this ...

Click event for jQuery horizontal accordion

I'm attempting to create a simple horizontal accordion-style element. My setup includes three 'banner' divs and three 'area' divs. Ideally, when I click on a banner, the corresponding area should animate - expanding in width to au ...

What are the scenarios where using multiple ng-app in Angular is recommended?

Is it considered best practice to have just one ng-app per page in an Angular application, or is it acceptable to have multiple ng-apps on a single page? If it is okay to use multiple ng-apps, what are the circumstances in which it is appropriate to have ...

Building a jQuery function to filter JSON data based on user input without relying on any external filter

Is it possible to dynamically filter a list of JSON data based on the value entered in a search input box for a specific key, such as 'firstname'? I am new to JavaScript and jQuery and would appreciate any help. HTML <input type="search" nam ...

Execute a PHP SQL query when a link is clicked

To trigger a SQL query when a link is clicked, I have implemented the following code: mainpage.php: function deleteImage1() { $.post("delete_image.php", { num:1, id:<?php echo $id; ?> }, function(data,status){ alert("Data: " + data + "\n ...

What are the steps to run and test the renovate bot on your local machine

Before setting up renovate to work with my Azure pipeline, I wanted to test it locally using npx renovate to ensure everything is working as expected and that my config file is properly configured. I ran npx renovate --platform local command. My project i ...

Cross-component communication in Angular

I'm currently developing a web-based application using angular version 6. Within my application, there is a component that contains another component as its child. In the parent component, there is a specific function that I would like to invoke when ...

Which JQuery plugins can transform regular <select> dropdowns into more stylish options?

After an extensive search, I was only able to locate one solution at this link. I scoured the entire internet for alternatives. ...

Dynamically setting properties in a Vue component using Angular

After browsing through this interesting discussion, I decided to create a web component: <my-vue-web-comp [userId]="1"></my-vue-web-comp> Initially, everything was working smoothly in Angular when I assigned a static property. Howeve ...

Guide to transforming a JSON file value into a JavaScript list

I need assistance with converting a string of comma-separated values in a JSON file into a list. The goal is to iterate through the list in a for loop and click on each element. Can you help me with this task? testdata.json : {"optionsList":&quo ...

Enhancing VueJS2 components by optimizing code structure to eliminate duplicate elements

The following code is used in two different components, so please avoid using props. Utilize data variables and largely similar methods but with different component templates. <template> </template> <script> export default { name ...

What is the best way to smoothly move a fixed-size div from one container to another during a re-render process?

Introduction Anticipated change Similar, though not identical to my scenario: Situation 0: Imagine you have a container (chessboard with divs for game pieces) and a dead-pieces-view (container for defeated pieces). The positioning of these containers i ...