mzereba
mzereba

Reputation: 2517

Looping through properties of object in an array in AngularJS

I would like to loop and print the properties of the array of objects (only one time)

Html

<div ng-app ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="(key, value) in items">{{key}}</li>
    </ul>
</div>

Script

function MyCtrl($scope) {
    $scope.items = [{'name':10, 'phone':11},{'name':10, 'phone':11}];
}

The desired effect would be:

name

phone

It works only if I have one object and not an array of objects

Here is a link to fiddle http://jsfiddle.net/3vzd732s/2/

Thanks in advance.

Upvotes: 0

Views: 1076

Answers (3)

paje007
paje007

Reputation: 1101

The code that you have given in the question seems to run correctly. In the fiddle istead of {{key}} you have given {{name}}.

If you know that it is going to be an array, how about pointing to the first element in the array?

<li ng-repeat="(key, value) in items[0]">{{key}}</li>

Upvotes: 1

Artem Petrosian
Artem Petrosian

Reputation: 2954

Updated solution after question clarification:

<div ng-app ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="item in items track by $index">
            <p ng-repeat="(key, value) in item">{{key}} {{value}}</p>
        </li>
    </ul>
</div>

You forgot to wrap your items in Array in your fiddle example, here is an updated one:

http://jsfiddle.net/3vzd732s/5/

Upvotes: 1

squiroid
squiroid

Reputation: 14017

<div ng-app ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="item in items">
            <p ng-repeat="(key,value) in item">
            {{key}} {{value}}

        </li>
    </ul>
</div>

Fiddle

UPDATE Change the answer for multiple objects.

Upvotes: 0

Related Questions