如何在AngularJs中将json数组转换为js数组?

时间:2015-02-26 08:41:32

标签: javascript arrays json angularjs

我从Angular和前端开发开始,似乎无法解决以下问题。

我已将一个变量重新分配给另一个变量:$ scope.testarray = $ scope.todos;但是当使用Angular绑定时,只会显示'todos'。

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

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

2 个答案:

答案 0 :(得分:1)

在您的代码中

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;写在then block之外。 $http.get是一个异步调用,因此,即使在定义$scope.todos之前,也会执行此行。

.then块中移动它将解决您的问题。假设此处声明了$scope.testarray

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

评论是否需要更多帮助。

答案 1 :(得分:0)

我只想使用$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;
  });
});