儿童JSON元素Angularjs
Json的代码工作正常,如果我调用页面与{{result.title}}
但如果我要打电话给author
孩子,JSON元素不起作用儿童JSON元素Angularjs
控制器
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope,$http) {
$http.get('post.json')
.then(function (response){
console.log(response.data);
$scope.results = response.data.pages,
$scope.resultauthor = response.data.author;
});
的Json示例
{
"pages": [
{
"id": 2,
"type": "page",
"modified": "2016-08-09 17:28:01",
"categories": [],
"author": {
"id": 1,
"name": "admin",
"description": ""
},
}
的Html
<div ng-repeat="item in resultauthor">
{{ item.name }}
</div>
我在哪里我的代码的问题呢?
您需要将resultsauthor
更改为resultauthor
。
<div ng-repeat="item in resultauthor">
{{ item.name }}
</div>
它不起作用 – Max
按照json
您提供response.data.author
将不存在。 首先需要从页面排列检索page
项目,然后得到那个特定元素的作者:
$http.get('post.json')
.then(function (response){
$scope.results = response.data.pages;
});
除此之外,尝试在你的控制台来检查是否有任何网络或JavaScript错误给你一个更好的反馈。
UPDATE
您还以错误的方式使用ng-repeat
(你需要遍历数组不是对象,以获得预期的行为)。
<div ng-repeat="item in results">
{{ item.author }}
</div>
检查this plunkr。
这并不完全清楚你想要做什么,但author
不是一个数组 - 它是一个对象。如果你想遍历author
的属性,那么你需要在你的ng-repeat
中使用(key, value) for object
语法。这里是一个例子(我不得不直接将json数据分配给$scope
属性,因为内联片段不支持外部文件,如post.json
文件)。
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.results = [{
"id": 2,
"type": "page",
"modified": "2016-08-09 17:28:01",
"categories": [],
"tags": [],
"title": "Title",
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
}
}];
$scope.resultauthor = $scope.results[0].author;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<body ng-app="myApp" ng-controller="customersCtrl">
<div ng-repeat="(key, value) in resultauthor">
{{ key }}: {{ value }}
</div>
<div ng-repeat="result in results">
<p>{{ result.title }}</p>
</div>
</body>
他在ng-repeat中使用$ scope.resultauthor,我想知道它是如何合理的,因为$ scope.resultauthor不是数组。 –
没错。这就是为什么我在我的回答中指出了这件事,并提供了一个循环对象属性和值的例子。 – Lex
您确定您的'$ http.get'将返回一个包含'author'对象?鉴于您提供的示例json,它看起来像'author'是'pages'数组中对象的子节点。 – Lex
Hi Lex,示例json它在注释之上它存储在文件“post.json”中 – Max
因此'$ scope.resultauthor'总是会被定义为undefined。虽然,我不明白'{{result.title}}'是如何工作的,因为你没有显示'$ scope.result'变量,你提供的示例json在任何地方都没有'title'属性。也许你应该编辑你的问题来提供[MCVE],然后可以提供更好的建议。 – Lex