【问题标题】:Importing a JSON on angularJS with $http.get使用 $http.get 在 angularJS 上导入 JSON
【发布时间】:2020-04-09 23:05:25
【问题描述】:

我正在学习 angularJs,我想从我的控制器上的 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>

【问题讨论】:

  • 控制台(浏览器)是否有错误? 'ng-app', 'ng-controller' 在 html 正文中吗?
  • @Mostav 我注意到我忘记了 ng-app,但我修复了它,现在只显示空的 标签
  • 如果可能的话,你能把整个 html 和 js 文件贴出来吗?没有所有必要元素的问题根本无济于事。
  • @Mostav 我已经编辑了帖子

标签: json angularjs


【解决方案1】:

获取 json 访问权限的正常方式是从 http 请求返回的对象中的数据 - 您正在使用整个返回的对象。

我使用“response”作为get 请求的返回值——那么数据就是“response.data”。这是必需的,因为在 get 请求的响应对象中返回了其他属性。

尝试将您的承诺更改如下:

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>

【讨论】:

  • 很高兴为您提供帮助 - 如果您可以将答案标记为已接受,以便其他开发人员知道问题已得到解决。快乐编码
【解决方案2】:

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
  });
});

更多: https://docs.angularjs.org/api/ng/service/$http

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签