简体   繁体   中英

AngularJS $http reading JSON data

How can i display data from an array of JSON data returned from the server in AngularJS? This is what i have, and for some reason i cannot display any data on my html page:

<script>
     function placesCtrl($scope, $http) {

          $http.get("http://somedomain/api/places_JSON.php")
          .success(function(response){
               $scope.names = response;
           });
          $scope.display = $scope.names[2].City;
      }
</script>

The JSON data that the $http.get is returning looks something like this:

[{City: "Berlin", Country: "Germany"},
{City: "Portland", Country: "USA"},
{City: "Barcelona", Country: "Spain"},
{City: "Paris", Country: "France"},
{City: "Cowes", Country: "UK"}]

Then the HTML code looks something like this:

<!DOCTYPE html>
<html>
<body>

<div ng-app="" ng-controller="placesCtrl">

<p> {{display}}</p>
</div>

So instead of displaying "Barcelona" as the result, it just displays {{display}}.

Any suggestions would be much appreciated.

Your problem is that the success callback is called after you set the scope variable. Move the variable assignment inside your callback function, and you should be fine.

Also, as ryeballar points out, it's highly recommended that you as you register an application in the ng-app directive. See the tutorial for details. Although you don't need it for a simple example like this, it will make your life much, much easier as you add more components.

You have to register your Controller. Try this:

var myApp = angular.module('myApp',[]);

myApp.controller('placesCtrl', ['$http','$scope', function($http, $scope) {
    $http.get("http://somedomain/api/places_JSON.php")
    .success(function(response){
        $scope.names = response;
    });
    $scope.display = $scope.names[2].City;
}]);

And edit your html:

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

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