5

Ich bin neu mit AngularJS und ich habe ein Problem beim Parsen einer JSON-Antwort. Dies ist der HTML-Code Ich verwende:Probleme beim Parsen einer JSON-Antwort mit AngularJS

<!DOCTYPE html> 
<html ng-app> 
<head> 
    <script src="@routes.Assets.at("javascripts/angular.min.js")" type="text/javascript"</script> 
    <script src="@routes.Assets.at("javascripts/carLibrary.js")" type="text/javascript"></script> 
</head> 
<body> 

<div ng-controller="CarCtrl"> 
    <ul> 
     <li ng-repeat="car in cars"> 
      {{car.name}} 
      <p>{{car.speed}}</p> 
     </li> 
    </ul> 
    <hr> 
    <p>{{response}}</p> 
</div> 
</body> 
</html> 

Und das ist die Javascript-Code AngularJS mit:

function CarCtrl($scope, $http) { 

    $scope.getAllCars = function() { 
     $scope.url = 'getAllCars'; 

     $http.get($scope.url).success(function (data, status) { 
      $scope.response = data; 
      var carsFromServer = JSON.parse(data); 
      $scope.cars = carsFromServer.allCars; 
     }).error(function (data, status) { 
       $scope.response = 'Request failed'; 
      }); 
    } 

    $scope.getAllCars(); 
} 

Die HTML ist die Variable $ scope.response mit dem JSON vom Server zurück zeigt, aber es zeigt nichts in der Liste an der Spitze. Der JSON ist perfekt formatiert, jedoch scheint $ scope.cars immer leer zu sein.

Was mache ich falsch?

Vielen Dank,

GA

+0

Können Sie ein Beispiel für den JSON zeigen, den Sie bekommen? – mael

Antwort

13

$ http.get die json für Sie analysieren. Sie müssen es nicht selbst analysieren.

$scope.cars = data.allCars; 
+0

Genie! Vielen Dank! –

3

einfach Ihre Daten wie die

function (response,httpStatus) {  
       alert('response' + angular.toJson(response));     
     } 

analysieren Es eingebaut ist Merkmal angularjs.