user3514822
user3514822

Reputation: 55

looping json object in ng-repeat

I have a JSON object containing {"id":1,"name":"name1"} which I get from a rest api and I want to display the name property in a list using ng-repeat. Below is what I have in my page:

 <ion-item ng-repeat="p in Names">
        {{p.name}}
 </ion-item> 

It does not display anything with above code and when I change {{ p.name }} to {{ Names }} it displays {"id":1,"name":"name1"}. Iterate and get each properties?

Upvotes: 1

Views: 2238

Answers (3)

UsainBloot
UsainBloot

Reputation: 816

Is your JSON object an array like this or just an object?

/* Array - Can ng-repeat on this */
Names = [{"id":1, "name":"name1"}]

/* Object - Cannot ng-repeat on this */
Names = {"id":1, "name":"name1"}

If it is just an object, ng-repeat will not be able to iterate.

You can see an example of this in action here.


Answering question below from user3514822

In the case of the comment below where JSON.parse could return an array of objects or just a single object.

var response = { "userlist": [ "{\"id\":1,\"name\":\"alex\"}" ] };

$scope.Names=JSON.parse( response.userlist );

if( Object.prototype.toString.call( $scope.Names ) !== '[object Array]' ) {
    $scope.Names = [ $scope.Names ];
}

After doing this the ng-repeat should work as you have already defined as $scope.Names should always be an array.

Upvotes: 2

Alexandru R
Alexandru R

Reputation: 8823

ng-repeat is used for lists (repeating things) like:

Names = [{"id":1,"name":"name1"}, {"id":2,"name":"name2"}, {"id":3,"name":"name3"}]

If you only have {"id":1,"name":"name1"} get rid of ng-repeat and simply use {{Names.name}}

<ion-content ng-controller="testPage">
   <ion-list>                                           
     <ion-item>
            {{Names.name}}
     </ion-item> 
  </ion-list>
</ion-content>

If you want to cover both cases just create an array. (when Names is only an object.

Names = angular.isObject(Names)?[Names]:Names;

Upvotes: 1

Jax
Jax

Reputation: 1843

try

{{Names.name}}

you can iterate over an array of objects, but if you have just one object, there's no need. You would need to iterate if you have something like this:

Names = [{"id":1,"name":"name1"}, {"id":2,"name":"name2"}, {"id":3,"name":"name3"}, ...]

in this case an ng-repeat="p in Names" would work fine by doing {{p.name}}.

Hope it helps

Upvotes: 1

Related Questions