[英]Importing a JSON on angularJS with $http.get
Im learnign angularJs, and i want to import an array from a json on my controller Like that:我正在学习 angularJs,我想从我的 controller 上的 json 导入一个数组 就像这样:
myApp.controller("demoCtrl", function ($scope, $http) {
var promise = $http.get("todo.json");
promise.then(function (data) {
$scope.todos = data;
});
});
and im using a table to display the data on todos
:我使用表格来显示
todos
上的数据:
<table class="table">
<tr>
<td>Action</td>
<td>Done</td>
</tr>
<tr ng-repeat="item in todos">
<td>{{item.action}}</td>
<td>{{item.done}}</td>
</tr>
</table>
and this results on the flowing html page:这在流动的 html 页面上产生:
<!DOCTYPE html>
<html ng-app="demo">
<head>
<title>Example</title>
<link href="../css/bootstrap.css" rel="stylesheet" />
<link href="../css/bootstrap-theme.css" rel="stylesheet" />
<script src="angular.js"></script>
<script type="text/javascript">
var myApp = angular.module("demo", []);
myApp.controller("demoCtrl", function ($scope, $http) {
var promise = $http.get("todo.json");
promise.then(function (data) {
$scope.todos = data;
});
});
</script>
</head>
<body ng-controller="demoCtrl">
<div class="panel">
<h1>To Do</h1>
<table class="table">
<tr>
<td>Action</td>
<td>Done</td>
</tr>
<tr ng-repeat="item in todos">
<td>{{item.action}}</td>
<td>{{item.done}}</td>
</tr>
</table>
</div>
</body>
The normal way of getting access to the json is from the data within the returned object from the http request - you are tying to use the entire returned object.访问 json 的正常方法是从 http 请求返回的 object 中的数据 - 您正在使用整个返回的 ZA8CFFDE8611AC
I use "response" as the return from the get request - then the data is "response.data".我使用“response”作为get请求的返回——那么数据就是“response.data”。 This is needed because there are other properties returned within the response object from the get request.
这是必需的,因为在 get 请求的响应 object 中返回了其他属性。
Try changing your promise to be as follows:尝试将您的 promise 更改为如下:
promise.then(function (response) {
$scope.todos = response.data;
});
Also you should be having a thead and th's and tbody in the table to show a more semantically correct table此外,您应该在表格中有一个 thead 和 th's 和 tbody 以显示一个语义更正确的表格
<table class="table">
<thead>
<tr>
<th scope="col">Action</th>
<th scope="col">Done</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in todos">
<td>{{item.action}}</td>
<td>{{item.done}}</td>
</tr>
</tbody>
</table>
Promise return entire response in callback Data is in response.data Promise 在回调中返回整个响应数据在 response.data
myApp.controller("demoCtrl", function ($scope, $http) {
var promise = $http.get("todo.json");
// Entire response in callback
promise.then(function (response) {
$scope.todos = response.data; // Data is in response.data
});
});
More: https://docs.angularjs.org/api/ng/service/$http更多: https://docs.angularjs.org/api/ng/service/$http
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.