0

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>
3
  • Sorry, forgot to add the json file... it's just the following in the file: [{ "text":"learn angular", "done":true }, { "text":"another todo", "done":true }]
    – P0lska
    Commented Feb 26, 2015 at 8:44
  • 1
    problem independent of angularjs, this is a reference issue, $scope.todos = res.data; todos will refer to new data, but testarray still refers to old todos object
    – mido
    Commented Feb 26, 2015 at 8:48
  • Thanks but how do I fix it :)?
    – P0lska
    Commented Feb 26, 2015 at 8:53

2 Answers 2

1

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.