问题
I'm trying to get Angular to display JSON data that I've managed to pull from a database via PDO. The PDO part and JSON encode part is working fine -- console is returning the data as expected.
However, when using ng-repeat the div
s do display but post.time
does not show.
HTML
<html ng-app="dataVis">
. . .
<body ng-controller="GraphController as graph">
<div ng-repeat="post in graph.posts track by $index">
{{post.time}}
</div>
</body>
</html>
JSON data
[
{
"time": "1340",
"postId": "282301",
"likes": "2"
},
{
"time": "1300",
"postId": "285643",
"likes": "0"
}
] . . . (etc)
JS
(function () {
var app = angular.module('dataVis', []);
app.controller('GraphController', ['$http', function ($http) {
var graph = this;
graph.posts = [];
$http.get('/query-general.php').success(function (data) {
console.log(data); // returns JSON data
graph.posts = data;
});
}]);
}());
At first I did not include track by $index
but upon receiving a dupes error I decided to include it.
I would like to display the JSON data in the HTML page using ng-repeat. Can anybody lend a helping hand to get this working?
回答1:
You need to declare $scope.graph variable at first, before you can pass data to $scope.graph.posts.
$scope.graph = {};
$scope.graph.posts = data;
Working example - JSFiddle http://jsfiddle.net/RkykR/294/
HTML
<h3>Ng-Repeat example</h3>
<div ng-app ng-controller="MyCtrl">
<table>
<thead>
<tr><td>time</td>
<td>postID</td>
<td>likes</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in graph.posts"><td>{{item.time}}</td>
<td>{{item.postId}}</td>
<td>{{item.likes}}</td>
</tr>
</tbody>
</table>
</div>
JavaScript
var data = [
{
"time": "1340",
"postId": "282301",
"likes": "2"
},
{
"time": "1300",
"postId": "285643",
"likes": "0"
}
];
function MyCtrl($scope) {
$scope.graph = {};
$scope.graph.posts = data;
}
CSS
table {
padding:5px;
width:500px;
}
table td {
border: 1px solid gray;
padding:3px 0;
text-align:center;
}
table thead td {
font-weight:bold;
}
回答2:
Because json is naming the properties as "time"
rather than time
, have you tried using array notation to access them?
e.g
<td>{{item["time"]}}</td>
<td>{{item["postId"]}}</td>
<td>{{item["likes"]}}</td>
回答3:
I resolved the issue. I had comments in my php files outside of the php tags. So when angular tries to get the JSON data from the php page, the comments were fetched too. Thanks for all the help.
来源:https://stackoverflow.com/questions/27142413/angularjs-ng-repeat-not-displaying-json