【问题标题】:Bind $index to ng-model in angular-ui-select在 angular-ui-select 中将 $index 绑定到 ng-model
【发布时间】:2016-04-20 12:45:45
【问题描述】:

我试图使用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')。

我已经准备好this plunker。

【问题讨论】:

    标签: angularjs angular-ui-select


    【解决方案1】:

    我找到了解决方法:

      <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 不是为此而设计的。

    【讨论】:

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

    如果你想要的只是 $index,那么你可以这样做:

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

    这会将 $select.selected 设置为 $index,这会更新您的 ng-model。

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

    【讨论】:

      【解决方案3】:
      <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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-24
        • 1970-01-01
        • 2015-01-19
        • 2023-04-07
        • 1970-01-01
        • 2014-07-12
        • 2015-08-01
        • 1970-01-01
        相关资源
        最近更新 更多