【发布时间】:2017-03-31 16:28:24
【问题描述】:
当我在select 中使用ng-options 循环我的列表并生成我的下拉列表时,是否可以将动态属性id 添加到option?如果我使用ng-repeat 循环,它会起作用,因为在那里我可以将属性id 直接放在option 标记中,并用$index 递增它。 ng-options 也可以这样做吗?这是我的代码:
angular.module("myApp", []).controller("myController", function($scope) {
$scope.selectedOption1;
$scope.selectedOption2;
$scope.myList = [{
text: "1"
}, {
text: "2"
}, {
text: "3"
}, {
text: "4"
}, {
text: "5"
}, ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<!--BUILD DROPDOWN WITH NG-OPTIONS LOOP-->
<select ng-model="selectedOption" ng-options="option as option.text for option in myList"></select>
<!--BUILD DROPDOWN AND SET ATTRIBUT ID WITH NG-REPEAT LOOP-->
<select ng-model="selectedOption2">
<option id="option_{{$index}}" ng-repeat="option in myList">{{option.text}}</option>
</select>
</div>
select 的屏幕截图(红色边框是 id):
有什么想法吗?谢谢。
【问题讨论】:
-
使用
ng-options,您只能设置option的text和value,而不能设置id。 -
@Aruna 好的,我期待这样的答案 - 谢谢。 :-)
-
@Aruna 如何修改 ng-options 循环中的值?目前,每个选项都有一个 0-5 的值(见屏幕截图)。我可以在那里设置一个文本并像在 ng-repeat 中那样用 $index 递增它吗?谢谢
-
是的,你可以,我会发布这个答案:-)
-
@Aruna 非常好,谢谢!
标签: html angularjs select ng-options