Angularjs 在angular ui select中将$index绑定到ng模型

Angularjs 在angular ui select中将$index绑定到ng模型,angularjs,angular-ui-select,Angularjs,Angular Ui Select,我试图使用ui-select指令将$index绑定到ng模型,但没有成功 <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 i

我试图使用
ui-select
指令将
$index
绑定到
ng模型
,但没有成功

<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>
<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>

在上面的模板中,
itemArray
是一个月名称数组,从下拉列表中选择任何月份后,我想将其
$index
绑定到
ng模型(即“selected.m”)


我已经准备好了plunker。

我找到了一种解决方法:

  <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仅在表达式的track by或循环内可用。此外,AngularJS是一个框架,它希望您操作对象,而不是像以前那样编制索引,这就是为什么我认为ng repeat/ng options不是设计用来这样做的。

我找到了一种解决方法:

  <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仅在表达式的track by或循环内可用。此外,AngularJS是一个框架,它希望您操作对象,而不是像以前那样进行索引,这就是为什么我认为ng repeat/ng options不是设计用来这样做的。

如果您只需要$index,那么您可以这样做:

<ui-select-choices repeat="$index in itemArray">
  <span ng-bind="itemArray[$index] + '' + $index"></span>
</ui-select-choices>

这会将$select.selected设置为更新ng模型的$index

{{selected}
{{$select.selected}

如果您只需要$index,则可以执行以下操作:

<ui-select-choices repeat="$index in itemArray">
  <span ng-bind="itemArray[$index] + '' + $index"></span>
</ui-select-choices>

这会将$select.selected设置为更新ng模型的$index

{{selected}
{{$select.selected}

{{vm.countries[vm.mySelectedCountry].countryName}

{{vm.countries[vm.mySelectedCountry].countryName}

很好的解决方案,但是让我们看看是否有人提供了一些解决方案:-)很好的解决方案,但是让我们看看是否有人提供了一些解决方案:-)