Error importing Dynamic Json via AngularJs

4

Hello, I'm having trouble importing this Json and others, I do not know what I might be doing wrong in this ...

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><scripttype="text/javascript">
    var app = angular.module('myApp', []);
    app.controller('heroisCtrl', function($scope, $http) {
       $http.get("https://angularjs.org/greet.php?callback=herois&name=Super%20Hero")
       .success(function(data) { $scope.names = data;});
    });
    </script>
</head>
<body>

<div ng-app="myApp" ng-controller="heroisCtrl">
<table>
  <tr ng-repeat="x in names">
    <td>{{ x.name }}</td>
    <td>{{ x.greeting }}</td>
  </tr>
</table>
</div>

</body>
</html>
    
asked by anonymous 10.07.2015 / 14:36

1 answer

4

It seems like you're mixing some things in the documentation of the Angular, I'll try to explain the problems:

  • This url you are using returns JSONP to bypass the access restriction policy to another domain. To receive data in this format, you must use the $http.jsonp method instead of $http.get .

  • According to the documentation for this method, the callback parameter of url must have the value JSON_CALLBACK , not herois as you are using. Otherwise the Angular will not know how to handle the result (if you want to keep your way, you would need to have a herois function that would handle the result).

  • The data returned by this URL looks like this:

    {"name":"Super Hero","salutation":"Dia Duit","greeting":"Dia Duit Super Hero!"}
    

    That is, it is an object, not an array. But the code in your view is treating it as if it were an array of objects, which would create a row in the table for each object with ng-repeat . This will not work with this data, you would need to eliminate the repeat and get the properties directly from the object.

  • Correcting these issues, your code would look like this:

    <html>
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><scripttype="text/javascript">
        var app = angular.module('myApp', []);
        app.controller('heroisCtrl', function($scope, $http) {
           $http.jsonp("https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero")
           .success(function(data) { $scope.dados = data;});
        });
        </script>
    </head>
    <body>
    
    <div ng-app="myApp" ng-controller="heroisCtrl">
    <table>
      <tr>
        <td>{{ dados.name }}</td>
        <td>{{ dados.greeting }}</td>
      </tr>
    </table>
    </div>
    
    </body>
    </html>
        
    10.07.2015 / 16:45