AngularJS - How can I reference the property name within an ng-Repeat
Asked Answered
L

2

138

In addition to rendering the value of the properties in an object, I'd also like to render the property name as a label. Is there a way to do this with ng-repeat? For example:

<ul>
    <li ng-repeat="option in data">{{propertyName}}: {{option}}</li>
</ul>

Which might spit out something like this:

<ul>
    <li>Name: John</li>
    <li>Phone: (123) 456-7890</li>
    <li>Country: England</li>
</ul>
Laruelarum answered 8/6, 2012 at 18:35 Comment(0)
P
342

Try this:

<ul>
    <li ng-repeat="(key,val) in data">{{key}}: {{val}}</li>
</ul>
Phenobarbital answered 8/6, 2012 at 19:31 Comment(3)
@Andy - they aren't so great, actually. They need more simple actual code examples like you have shown here. Thanks for your answer and please keep posting to StackOverflow; your post really helped me understand how to access the AngularJS docs. Best regards and upvote!Suet
so easy but didn't think of it :D tnx!Revulsive
what to do if i have a function like --- myFunc(key) --- that need the key value this gonne show me the name key in html and not the valueWobble
R
28

The problem with documentation is that it says (key, value) with that space ... it took me some time to figure out that because of that it doesn't work

Rugger answered 29/10, 2012 at 16:4 Comment(5)
Thanks so much. You are right. You cannot have a space between the comma and the value. (key,value) not (key, value).Trample
Maybe things are different in newer releases of Angular, but you can have a space between (key, val). That's often how I do it.Epsom
I found (key, value) didn't work for me. Are you saying it's because of the whitespace??? Geez! But thanks.Babbler
Works for me with the space as well.Romano
val vs value affecting the space?Stokehole

© 2022 - 2024 — McMap. All rights reserved.