gpt4 book ai didi

javascript - Angular 1.3 - 将 Id 添加到 ng-options 内的选项标签

转载 作者:太空宇宙 更新时间:2023-11-04 15:48:16 24 4
gpt4 key购买 nike

我正在使用 Angular 1.3.8 。我有一个使用数组作为 ngOptions 选项的选择列表,语法包括基本的 track by表达。

我需要能够向选项的 ID 属性添加唯一值(当 color 创建选项标记时,从当前 description<option> 到当前 ng-options 元素。有吗有办法做到这一点吗?如果没有,我可以使用 ng-repeat 吗?我已经尝试了 ng-repeat 但没有成功。

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

$scope.colors = [{
"code": "GR",
"description": "Green"
}, {
"code": "RE",
"description": "Red"
}, {
"code": "CY",
"description": "Cyan"
}, {
"code": "MG",
"description": "Magenta"
}, {
"code": "BL",
"description": "Blue"
}];

// Preselect CYAN as default value
$scope.data = {
colorType: $scope.colors[2]
}

});
<script src="https://code.angularjs.org/1.3.8/angular.min.js"></script>
<div ng-app="plunker">
<div ng-controller="MainCtrl">
<strong>ng-options: </strong><select name="color" id="colors" ng-model="data.colorType" ng-options="color as color.description for color in colors track by color.code"></select>
<strong>ng-repeat: </strong><select name="color" id="colors" ng-model="data.colorType">
<option ng-repeat="color in colors" value="{{color}}">{{color.description}}</option>
</select>
<pre>{{ data | json }}</pre>
</div>
</div>

最佳答案

一种选择是使用 ngRepeat使用表达式中的语法 (key, value)

(key, value) in expression where key and value can be any user defined identifiers, and expression is the scope expression giving the collection to enumerate.

使用该语法,可以添加键(例如index):

<option ng-repeat="(index, color) in colors" value="{{color}}" id="option_{{index}}">{{color.description}}</option>

请参阅下面的演示。检查选项应显示 id 属性集(例如 option_0option_1 等)。

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

$scope.colors = [{
"code": "GR",
"description": "Green"
}, {
"code": "RE",
"description": "Red"
}, {
"code": "CY",
"description": "Cyan"
}, {
"code": "MG",
"description": "Magenta"
}, {
"code": "BL",
"description": "Blue"
}];

// Preselect CYAN as default value
$scope.data = {
colorType: $scope.colors[2]
}

});
<script src="https://code.angularjs.org/1.3.8/angular.min.js"></script>
<div ng-app="plunker">
<div ng-controller="MainCtrl">
<strong>ng-repeat: </strong><select name="color" id="colors" ng-model="data.colorType">
<option ng-repeat="(index, color) in colors" value="{{color}}" id="option_{{index}}">{{color.description}}</option>
</select>
<pre>{{ data | json }}</pre>
</div>
</div>

关于javascript - Angular 1.3 - 将 Id 添加到 ng-options 内的选项标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43375159/

24 4 0