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

标签 javascript arrays json angularjs

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

我已将一个变量重新分配给另一个变量:$scope.testarray = $scope.todos;但是当使用 Angular 绑定(bind)时,只会显示“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>

最佳答案

在你的代码中

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 block 内将解决您的问题。假设此处声明了 $scope.testarray

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

如果您需要更多帮助,请发表评论。

关于javascript - 如何在 AngularJs 中将 json 数组转换为 js 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28737792/

相关文章:

javascript - Ajax 调用未获取数据

javascript - 直接在ReactJS中的类定义上设置字段

javascript - 什么时候可以将管道运算符用于条件参数? - JavaScript

javascript - Puppeteer 集群示例抛出错误 : Unable to get browser page

javascript - 正则表达式:匹配 '+' 之前的所有字符,如果 '+' 不存在,则匹配整个字符串

ios - 如何访问数组中自定义对象的值?

c++ - 在 C++ 中有效地规范化数组

c - 使用 C,在初始化结构数组时,似乎第一列和最后一列重叠

java - 响应不包含零整数

javascript - 如何使用 jQuery 解析字符串/URL