Harsh sachdev Harsh sachdev - 3 months ago 5
AngularJS Question

ng-repeat is not showing anything

Here is my code and ng-repeat generated the list but not showing anything.

<!DOCTYPE html>
<html lang="en">
<head>


</head>
<body ng-app="myApp">

<div ng-controller="getHospitalCtrl">

<h3>my list</h3>
<ul>
<li ng-repeat="hospital in hospitals track by $index">
<p class="name">{{hospital.name}}</p>
<p class="location">{{hospital.address.city}}</p>
</li>
</ul>
</div>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('myApp',[]);
app.controller('getHospitalCtrl',function($scope, $http){

console.log('i m in getHospitalCtrl');

$http.get("url")
.then(function(response){
$scope.hospitals = JSON.stringify(response.data.data);
console.log($scope.hospitals);
//this console is printing the right json here
});

});
</script>

</body>
</html>


The json in console is like this

[{"_id":"57a5877bb23cda352156315a","userId":257,"name":"Fortis","email":"fortis@hospital.com","description":"Fortis description for testing","address":{"postalCode":"110088","state":"DL","city":"New Delhi","streetAddress":"s-fortis"},"coordinate":{"coordinates":[77.1545846,28.7164134],"type":"Point"}}]

Answer

Look at your code:

First you have

$scope.hospitals = response.data;

which initializes $scope.hospitals to what is returned in the http response.

But immediately after you have

$scope.hospitals = JSON.stringify($scope.hospitals.data);

So you're overwriting this value with a string. Using ng-repeat on a string doesn't make sense. ng-repeat is used to iterate over an array.

You should just have one initialization:

$scope.hospitals = response.data.data;
Comments