【问题标题】:How to bind ng-model to the "value" of selected item for ui-select如何将 ng-model 绑定到 ui-select 所选项目的“值”
【发布时间】:2023-04-07 20:15:02
【问题描述】:

请查看以下内容: http://plnkr.co/edit/fc9XcyyYGtAk0aGVV35t?p=preview

  <ui-select ng-model="fm.countryCode" id="countryCode">
      <ui-select-match placeholder="Select a country...">{{$select.selected.label}}</ui-select-match>
      <ui-select-choices repeat="item in countries | filter: $select.search" value="{{$select.selected.value}}">
          <div ng-bind-html="item.label | highlight: $select.search"></div>
          <small ng-bind-html="item.value | highlight: $select.search"></small>
      </ui-select-choices>
  </ui-select>   

我正在尝试让 ui-select 将 fm.countryCode 设置为所选项目的值。目前它只是将 fm.countryCode 设置为整个国家项目。例如,如果我选择阿富汗,fm.countryCode 将设置为 {"value":"AF","label":"Afghanistan"}。我想要的是“AF”。

我必须设置一个 $watch 来实现这一点还是有更优雅的解决方案?

【问题讨论】:

标签: angularjs


【解决方案1】:

您可以将您的 ui-select 更改为:

<ui-select ng-model="fm.countryCode" id="countryCode">
  <ui-select-match placeholder="Select a country...">{{$select.selected.label}}</ui-select-match>
  <ui-select-choices repeat="item.value as item in countries | filter: $select.search" value="{{$select.selected.value}}">
      <div ng-bind-html="item.label | highlight: $select.search"></div>
      <small ng-bind-html="item.value | highlight: $select.search"></small>
  </ui-select-choices>
</ui-select>  

这会将 item.value 作为完整的项目,而不是 value 和 label。

所以重复部分:&lt;ui-select-choices repeat="item.value as item in countries 可以解决问题。

【讨论】:

    【解决方案2】:

    改变一下

    fm.countryCode = {{fm.countryCode}}
    

    fm.countryCode = {{fm.countryCode.value}}
    

    【讨论】:

      【解决方案3】:

      好的替换

       fm.countryCode = {{fm.countryCode}}
      

       fm.countryCode = {{fm.countryCode.value}}
      

      见 plunker http://plnkr.co/edit/EoBl4YZ6QfnJdHfOMM10?p=preview

      【讨论】:

      • 我不认为他的最终目标只是在他的 html 上显示 fm.countryCode 的值。
      【解决方案4】:

      IMO 更优雅的解决方案是:

      改变这个:

      <ui-select ng-model="fm.countryCode" id="countryCode">
           <ui-select-match placeholder="Select a country...">{{$select.selected.label}}</ui-select-match>
           <ui-select-choices repeat="item in countries | filter: $select.search" value="{{$select.selected.value}}">
                    <div ng-bind-html="item.label | highlight: $select.search"></div>
                    <small ng-bind-html="item.value | highlight: $select.search"></small>
           </ui-select-choices>
       </ui-select>
      

      到这里:

      <select ng-options="country.value as country.label for country in countries" ng-model="fm.countryCode"> </select>
      

      plunkr

      【讨论】:

        猜你喜欢
        • 2015-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-25
        • 1970-01-01
        • 1970-01-01
        • 2015-01-19
        相关资源
        最近更新 更多