Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  151] [ 1]  / answers: 1 / hits: 46641  / 11 Years ago, mon, july 29, 2013, 12:00:00

I am new using AngularJS and I am having an issue parsing a json response. This is the HTML code I am using:



<!DOCTYPE html>
<html ng-app>
<head>
<script [email protected](javascripts/angular.min.js) type=text/javascript</script>
<script [email protected](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>


And this is the Javascript code using AngularJS:



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


The HTML is showing the variable $scope.response with the JSON returned by the server, but it is not showing anything in the list at the top. The JSON is perfectly formatted, however $scope.cars variable seems to be always empty.



What am I doing wrong?



Many thanks,



GA


More From » json

 Answers
12

$http.get will parse the json for you. You do not need to parse it yourself.



   $scope.cars = data.allCars;

[#76683] Friday, July 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
haylie

Total Points: 26
Total Questions: 108
Total Answers: 104

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
;