如何通过AngularJS从json URL显示表?

时间:2018-12-03 09:17:03

标签: javascript html angularjs

我是Angular JS的新手,我正在学习如何从URL创建表。我在网上找到了此代码,以显示如何将URL中的信息显示到表中,但是它不起作用,你们能帮我检查一下吗。谢谢。

<!DOCTYPE html>
<html>

<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
</head>

<body>
  <div ng-app="" ng-controller="planetController"> 
    <table>
      <tr>
        <th>Planet</th>
        <th>Distance</th>
      </tr>
      <tr ng-repeat="x in names">
        <td>{{ x.name}}</td>
        <td>{{ x.distance}}</td>
      </tr>
    </table>
  </div>

  <script>
  function planetController($scope, $http) {
    $http.get("http://www.bogotobogo.com/AngularJS/files/Tables/planet.json")
    .success(function(response) {$scope.names = response;});
  }
  </script>

</body>
</html>

2 个答案:

答案 0 :(得分:2)

您需要定义一个init()函数并定义您的api调用。

<div ng-app="myApp" ng-controller="customersCtrl"  ng-init="init()"> 
  <table>
   <tr ng-repeat="x in names">
     <td>{{ x.name }}</td>
     <td>{{ x.distance }}</td>
   </tr>
   </table>
   </div>

  function init(){
     $http.get("http://www.bogotobogo.com/AngularJS/files/Tables/planet.json")
     .success(function(response) {
        $scope.names = response;
      });
  }

希望这可以解决您的问题。

答案 1 :(得分:0)

您的代码似乎还可以。

通过在浏览器控制台中打印响应来检查URL响应。 我认为,您收到URL(http://www.bogotobogo.com/AngularJS/files/Tables/planet.json)的CORS错误。

只需遍历下面的代码即可使用本地数据而不是API / URL创建表。

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="customersCtrl"> 

<table>
  <tr ng-repeat="x in names">
    <td>{{ x.name }}</td>
    <td>{{ x.distance }}</td>
  </tr>
</table>

</div>

<script>
var app = angular.module('myApp', []);

app.controller('customersCtrl', function($scope, $http) {
    $scope.names= [
  {"name":"Neptune", "distance":30.087},
  {"name":"Uranus", "distance":19.208},
  {"name":"Saturn", "distance":9.523}, 
  {"name":"Jupiter", "distance":5.203}, 
  {"name":"Mars", "distance":1.524}, 
  {"name":"Earth", "distance":1.0}, 
  {"name":"Venus", "distance":0.723}, 
  {"name":"Mercury", "distance":0.387}    
]
});
</script>

</body>
</html>