只有在迭代JSON对象时,键才使用更简洁的ng-repeat语法

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

本文关键字:简洁 语法 ng-repeat 迭代 JSON 对象      更新时间:2023-09-26

我使用ng-repeat="(key, value)"语法来迭代JSON对象,但当我使用复选框时,我实际上从未需要value变量。是否有更简洁的方法来做以下事情:

EDIT: HAML有些令人困惑,所以这里是普通的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>

请注意,我实际上将attribute用于ng-model(仅绑定到value时不能正常工作)和复选框标签。这把钥匙是逃不掉的。我不需要的是变量。

这是真的,你可以做ng-repeat: "value in object",但value不能正确地绑定在复选框上,而且,再一次,没有给我一些东西用于标签:

<!-- "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>

下面是演示上述内容的示例:http://jsfiddle.net/Zb5bA/8/

不可能只迭代键,所以必须使用

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

此处不能忽略value