我试图使用ui-select
指令将$index
绑定到ng-model
,但没有成功。
<ui-select ng-model="selected.m">
<ui-select-match>
<span ng-bind="$select.selected.name"></span>
</ui-select-match>
<ui-select-choices repeat="$index as choice in itemArray">
<span ng-bind="choice + '' + $index"></span>
</ui-select-choices>
</ui-select>
在上面的模板中,itemArray
是一个月名称数组,从下拉列表中选择任何一个月后,我想将其$index
绑定到ng-model
(即"selected.m")
我已经准备好了。
我找到了解决这个问题的方法:
<ui-select ng-model="dummy" ng-change="selected.m=itemArray.indexOf(dummy)">
<ui-select-match>
<span ng-bind="$select.selected.name"></span>
</ui-select-match>
<ui-select-choices repeat="choice in itemArray">
<span ng-bind="choice + '/' + $index"></span>
</ui-select-choices>
</ui-select>
这是必要的,因为$index仅在表达式的trackby或循环中可用。此外,AngularJS是一个框架,它希望您操作对象,而不是像以前那样索引,这就是为什么我认为ng repeat/ng选项不是为了这样做而设计的。
如果你只想要$index,那么你可以这样做:
<ui-select-choices repeat="$index in itemArray">
<span ng-bind="itemArray[$index] + '' + $index"></span>
</ui-select-choices>
这会将$select.selected设置为$index,后者将更新ng模型。
<pre> {{ selected }} </pre>
<ui-select ng-model="selected.m">
<ui-select-match>
<span>{{$select.selected}}</span>
</ui-select-match>
<ui-select-choices repeat="$index in itemArray">
<span ng-bind="itemArray[$index] + '' + $index"></span>
</ui-select-choices>
</ui-select>
<ui-select ng-model="vm.mySelectedCountry" title="Choose a country" ng-required="true">
<ui-select-match placeholder="">{{vm.countries[vm.mySelectedCountry].countryName}}</ui-select-match>
<ui-select-choices repeat="$index in vm.countries| filter: $select.search">
<span ng-bind-html="vm.countries[$index].countryName | highlight: $select.search"></span>
</ui-select-choices>
</ui-select>