P0lska
P0lska

Reputation: 471

How do I turn a json array into a js array in AngularJs?

I'm starting out in Angular and front end development and can't seem to solve the following.

I have reassigned one variable to another: $scope.testarray = $scope.todos; but when using the Angular bindings, only the 'todos' will get displayed.

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;
});

and html:

<!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>

Upvotes: 0

Views: 98

Answers (2)

mido
mido

Reputation: 25054

I would just use a $scope.$watch,

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;
  });
});

Upvotes: 0

Aniket Sinha
Aniket Sinha

Reputation: 6031

In your code

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;
});

$scope.testarray = $scope.todos; is written outside of then block. $http.get is an asynchronous call, therefore, this line will be executed even before $scope.todos is defined.

Moving this inside .then block will solve your problem. Assuming $scope.testarray is declared here.

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

Comment if you need more help.

Upvotes: 1

Related Questions