Html 如何在 AngularJS 的循环内使用标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14663397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use labels inside loops with AngularJS
提问by Aaron Yodaiken
So I'm inside an ng-repeat
like this:
所以我在里面是ng-repeat
这样的:
<li ng-repeat="x in xs">
<form>
<label for="UNIQUELABEL">name</label>
<input id="UNIQUELABEL">
<label for="ANOTHERUNIQUELABEL">name2</label>
<input id="ANOTHERUNIQUELABEL">
</form>
</li>
Which should produce something like
哪个应该产生类似的东西
<li>
<form>
<label for="UNIQUELABEL1">name</label>
<input id="UNIQUELABEL1">
<label for="ANOTHERUNIQUELABEL1">name2</label>
<input id="ANOTHERUNIQUELABEL1">
</form>
</li>
<li>
<form>
<label for="UNIQUELABEL2">name</label>
<input id="UNIQUELABEL2">
<label for="ANOTHERUNIQUELABEL2">name2</label>
<input id="ANOTHERUNIQUELABEL2">
</form>
</li>
...
I'm new to AngularJS and not sure of the right way to approach this (none of the docs use label
at all).
我是 AngularJS 的新手,不确定解决这个问题的正确方法(根本没有使用任何文档label
)。
采纳答案by Gleno
Since ng-repeat
provides a new scope object on each iteration, I prefer using something like
由于ng-repeat
在每次迭代中提供了一个新的范围对象,我更喜欢使用类似的东西
<li ng-repeat="x in xs">
<form>
<label for="UNIQUELABEL{{::$id}}_1">name</label>
<input id="UNIQUELABEL{{::$id}}_1">
<label for="UNIQUELABEL{{::$id}}_2">name2</label>
<input id="UNIQUELABEL{{::$id}}_2">
</form>
</li>
The advantage of this method is that you are guranteed not to have a duplicate selector with same id on the document. Duplicates could otherwise easily arise when routing or animating.
这种方法的优点是您保证不会在文档上有具有相同 id 的重复选择器。否则在路由或动画时很容易出现重复。
回答by Liviu T.
The correct solution is Gleno's.
正确的解决方案是 Gleno 的。
$id
is guaranteed to be unique for every created scope, while $index
changes with any change to the count of the underlining collection.
$id
保证对于每个创建的范围都是唯一的,而$index
随着下划线集合计数的任何变化而变化。
You need to add the $index property(zero based) that is available on the scope in the repeater
您需要添加在中继器范围内可用的 $index 属性(从零开始)
<li ng-repeat="x in xs">
<form>
<label for="UNIQUELABEL{{$index+1}}">name</label>
<input id="UNIQUELABEL{{$index+1}}">
<label for="ANOTHERUNIQUELABEL{{$index+1}}">name2</label>
<input id="ANOTHERUNIQUELABEL{{$index+1}}">
</form>
</li>
回答by Robert
For many scenarios, a better solution might be to enclose both the <input>
and label text in a single <label>
element. This is perfectly valid HTML, works properly in all browsers, and has the added benefit of being easy to use with hierarchical data, since you don't need to use the iterator variable:
对于许多场景,更好的解决方案可能是将 the<input>
和 label 文本包含在单个<label>
元素中。这是完全有效的 HTML,可以在所有浏览器中正常工作,并且具有易于与分层数据一起使用的额外好处,因为您不需要使用迭代器变量:
<li ng-repeat="x in xs">
<label>
Label Text
<input type="text">
</label>
</li>