【问题标题】:AngularJS: ng-repeat not displaying JSONAngularJS:ng-repeat 不显示 JSON
【发布时间】:2014-11-26 06:08:13
【问题描述】:

我试图让 Angular 显示我通过 PDO 从数据库中提取的 JSON 数据。 PDO 部分和 JSON 编码部分工作正常——控制台按预期返回数据。

但是,当使用 ng-repeat 时,divs 会显示,但 post.time 不会显示。

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 数据

[
    {
        "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;
    });

  }]);

}());

起初我没有包含track by $index,但在收到欺骗错误后我决定包含它。

我想使用 ng-repeat 在 HTML 页面中显示 JSON 数据。任何人都可以伸出援助之手来完成这项工作吗?

【问题讨论】:

  • 请把所有东西都放在这里。
  • 您确认HTTP请求成功返回数据了吗?
  • 是的,数据返回成功。 console.log(data) 返回预期的 JSON 数据

标签: javascript json angularjs angularjs-ng-repeat


【解决方案1】:

您需要先声明 $scope.graph 变量,然后才能将数据传递给 $scope.graph.posts。

$scope.graph = {};
$scope.graph.posts = data;

工作示例 - 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;
}

【讨论】:

  • 不正确,本题使用“controller as”语法,不需要注入$scope,也不需要在$scope上注册graph。图 === $scope。
【解决方案2】:

因为 json 将属性命名为 "time" 而不是 time,您是否尝试过使用数组表示法来访问它们? 例如

<td>{{item["time"]}}</td>
<td>{{item["postId"]}}</td>
<td>{{item["likes"]}}</td>

【讨论】:

    【解决方案3】:

    我解决了这个问题。我在 php 标签之外的 php 文件中有 cmets。因此,当 Angular 尝试从 php 页面获取 JSON 数据时,也会获取 cmets。感谢大家的帮助。

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 2015-09-07
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多