我有一个list
任务数:
[{
Titel: "Title1",
Position: "9"
},{
Titel: "Title2",
Position: "1"
},{
Titel: "Title3",
Position: "5"
},{
Titel: "Title4",
Position: "7"
}]
我正在尝试创建一个 list
的<select>
,其中每个是 list.lenght
长并且具有选定的值。 html 片段:
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="ms-authoringcontrols"><b>Title</b></td>
<td class="ms-authoringcontrols"><b>Position</b></td>
</tr>
<tr ng-repeat="t in tasks">
<td>
<a href="TODO">{{t.Titel}}</a>
</td>
<td>
<select ng-model="t.Position" ng-options="t.Position as tasks.indexOf(i)+1 for i in tasks"></select>
</td>
</tr>
</table
它缺少的是每个 <select>
的选定值(位置) 。我知道该值是通过定义 ng-model 和 ng-model="t.Position"
设置的是错误的,但是我该如何设置 Position
每个项目与其相关的值 select
元素? <option>
每个 select
应该是任务的长度并从 1 到 n 排序。
最佳答案
你非常接近,ngOptions您要查找的格式是select as label for value in array
,其中select
是将分配给模型的值。
在您的情况下,Position 是字符串,因此我们也需要将 select
转换为字符串,以便它与模型匹配:
ng-options="(tasks.indexOf(i)+1).toString() as tasks.indexOf(i)+1 for i in tasks"
^ model value ^ display
( tasks.indexOf(i)+1+''
也可以)
angular
.module('Test', [])
.controller('TestCtrl', function($scope) {
$scope.tasks = [{
Titel: "Title1",
Position: "9"
},{
Titel: "Title2",
Position: "1"
},{
Titel: "Title3",
Position: "3"
},{
Titel: "Title4",
Position: "2"
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="Test" ng-controller="TestCtrl">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="ms-authoringcontrols"><b>Title</b></td>
<td class="ms-authoringcontrols"><b>Position</b></td>
</tr>
<tr ng-repeat="t in tasks">
<td>
<a href="TODO">{{t.Titel}}</a>
</td>
<td>
<select ng-model="t.Position" ng-options="(tasks.indexOf(i)+1).toString() as tasks.indexOf(i)+1 for i in tasks"></select>
</td>
</tr>
</table>
<pre>{{tasks|json}}</pre>
</div>
(If you run the snippet you will notice the first is not selected, that's because [1,2,3,4] doesn't contain 9.)
关于javascript - 如何在 ng-repeat 中使用 ng-options 绑定(bind) <select> ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47351650/