简体   繁体   English

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

[英]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. 我开始进行Angular和前端开发,似乎无法解决以下问题。

I have reassigned one variable to another: $scope.testarray = $scope.todos; 我已经将一个变量重新分配给另一个变量:$ scope.testarray = $ scope.todos; but when using the Angular bindings, only the 'todos' will get displayed. 但是使用Angular绑定时,只会显示“待办事项”。

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

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. 写在then块之外。 $http.get is an asynchronous call, therefore, this line will be executed even before $scope.todos is defined. $http.get是一个异步调用,因此,即使在定义$scope.todos之前,也将执行此行。

Moving this inside .then block will solve your problem. 将其移入.then块将解决您的问题。 Assuming $scope.testarray is declared here. 假设在这里声明了$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 }); });

Comment if you need more help. 如果您需要更多帮助,请发表评论。

I would just use a $scope.$watch , 我只会使用$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;
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM