[英]Importing a JSON on angularJS with $http.get
我正在学习 angularJs,我想从我的 controller 上的 json 导入一个数组 就像这样:
myApp.controller("demoCtrl", function ($scope, $http) {
var promise = $http.get("todo.json");
promise.then(function (data) {
$scope.todos = data;
});
});
我使用表格来显示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>
这在流动的 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>
访问 json 的正常方法是从 http 请求返回的 object 中的数据 - 您正在使用整个返回的 ZA8CFFDE8611AC
我使用“response”作为get请求的返回——那么数据就是“response.data”。 这是必需的,因为在 get 请求的响应 object 中返回了其他属性。
尝试将您的 promise 更改为如下:
promise.then(function (response) {
$scope.todos = response.data;
});
此外,您应该在表格中有一个 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 在回调中返回整个响应数据在 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
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.