iftheshoefritz
iftheshoefritz

Reputation: 6129

Neater ng-repeat syntax for keys only when iterating JSON object

I use the ng-repeat="(key, value)" syntax to iterate a JSON object, but I never actually need the value variable when I'm working with checkboxes. Is there a neater way to do the following:

EDIT: HAML was confusing some, so here is plain HTML/angular:

<!-- "(key, val) in object" allows me to do everything, but value variable is wasted -->
<label ng-repeat="(attribute, value) in object">
    <input type="checkbox" ng-model="object[attribute]"/>
    {{attribute}}
</label>

Notice that I actually use attribute for the ng-model (which does not work properly when just binding to value) and for the checkbox label. There is no escaping the key here. What I do not need is the value variable.

It is true that you can do ng-repeat: "value in object", but value does not bind properly on the checkbox, and, again, does not give me something to use for the label:

<!-- "val in object" does not give me a label for checkboxes, and does not bind correctly -->
<label ng-repeat="value in object">
    <input type="checkbox" ng-model="value"/> <!-- changing this checkbox does not update the parent scope -->
    {{attribute}} <!-- does not exist in scope -->
</label>

Here is a fiddle demonstrating the above: http://jsfiddle.net/Zb5bA/8/

Upvotes: 0

Views: 640

Answers (1)

Jeetendra Chauhan
Jeetendra Chauhan

Reputation: 1977

there is no-way to iterate only on keys, so you have to use

ng-repeat="(key, value) in object"

you can't ignore value here.

Upvotes: 3

Related Questions