0

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.

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

It does run correctly when I have one object, but the issue is when I have an array and I want to read the properties names of the first element for instance. Try with my array above.
How about this?<li ng-repeat="(key, value) in items[0]">{{key}}</li>
1

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/

7 Comments

But the idea is to build the labels dynamically. I am not suppose to know what the properties are.
so, you have to use second ng-repeat inside to achieve this
One to loop the array to extract the first object, then one for the element to loop through it's properties?
yep, that's exactly what we did.
and track by $index is recommended to avoid dupes in Array docs.angularjs.org/error/ngRepeat/dupes
|
0
<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.

4 Comments

And one thing you are using angular version 1.0.3 and ng-repeat has track by feature enable from 1.2.0
Same issue. Look at my comment to paje007, try with my array above.
Close thanks, But one time only! it is like printing the labels for a table header
Oops sorry miss the <p > tag ending

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.