2016-09-15 89 views
0

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> 

我在哪裏我的代碼的問題呢?

+0

您確定您的'$ http.get'將返回一個包含'author'對象?鑑於您提供的示例json,它看起來像'author'是'pages'數組中對象的子節點。 – Lex

+0

Hi Lex,示例json它在註釋之上它存儲在文件「post.json」中 – Max

+0

因此'$ scope.resultauthor'總是會被定義爲undefined。雖然,我不明白'{{result.title}}'是如何工作的,因爲你沒有顯示'$ scope.result'變量,你提供的示例json在任何地方都沒有'title'屬性。也許你應該編輯你的問題來提供[MCVE],然後可以提供更好的建議。 – Lex

回答

0

您需要將resultsauthor更改爲resultauthor

<div ng-repeat="item in resultauthor"> 
    {{ item.name }} 
</div> 
+0

它不起作用 – Max

0

按照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。

+0

不起作用沒有在我的控制檯上的錯誤,你可以在這裏看到http://plnkr.co/edit/2x177MlVq1RSLIemriQ5?p =預覽 – Max

+0

@max實際上是在工作:問題在於你在對象中使用ng,所以行爲不像你想象的那樣。答案已更新。 – ianaya89

0

這並不完全清楚你想要做什麼,但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>

+0

他在ng-repeat中使用$ scope.resultauthor,我想知道它是如何合理的,因爲$ scope.resultauthor不是數組。 –

+0

沒錯。這就是爲什麼我在我的回答中指出了這件事,並提供了一個循環對象屬性和值的例子。 – Lex