简体   繁体   中英

How to display table from json URL by AngularJS?

i'm new to Angular JS, and i'm learning how to create a table from the URL. I found this code online to show how to display the information in the URL into table but it wont work, can you guys help me check this out. Thank you.

<!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>

You need to define a init() function and define your api call.

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

Hope this will fix your issue.

your code seems to fine.

Check your URL response by printing the response in Browser console. I think, you are getting CORS error for the URL( http://www.bogotobogo.com/AngularJS/files/Tables/planet.json ).

Just go through below code for creating table using local data instead of 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM