-1

我是 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>
4

2 回答 2

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

希望这能解决您的问题。

于 2018-12-03T10:34:36.000 回答
0

你的代码似乎很好。

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

只需通过以下代码使用本地数据而不是 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>
于 2018-12-03T09:42:21.737 回答