如何在维护模型的同时更改md选择框的显示文本

How to change the display text of md-select box while maintaining the model?

本文关键字:md 选择 文本 显示 维护 模型      更新时间:2023-09-26

我正在使用Angular材质库指令md-select向我的用户显示一组国家代码。在选择菜单中,我想显示国家/地区名称和国家/地区拨号代码,但一旦选择了国家/地区,我想在选择框中只显示其拨号代码。

前任。在选择India (+91)选项时,选择框的文本应为+91。我使用的代码如下。

<md-select ng-model="ctrl.selectedCountry" ng-model-options="{trackBy: '$value.code && $value.name && $value.prefix'}">
        <md-option ng-repeat="country in ctrl.countries" ng-value= "{{ country }}" >
                    {{ country.name }} ({{ country.prefix }})
        </md-option>
</md-select>

我不知道如何实现这一点,因为这种方式会导致与选择时的md-option标记中完全相同的显示文本。有没有一种方法可以在不更改ng-model绑定的情况下根据所选值指定显示文本模板?

试试这个:

<md-select ng-model="ctrl.selectedCountry" ng-model-options="{trackBy: '$value.code && $value.name && $value.prefix'}">
        <md-option ng-repeat="country in ctrl.countries" ng-value= "{{ country }}" >
                    {{ctrl.selectedCountry.prefix === country.prefix ? country.code : (country.name + ' (' + country.prefix + ')')}}
        </md-option>
</md-select>

由于角材料1.0.8有md-selected-text,所以您可以尝试:

<md-select md-selected-text="ctrl.selectedCountry.prefix" ng-model="ctrl.selectedCountry" ng-model-options="{trackBy: '$value.code && $value.name && $value.prefix'}">
  <md-option ng-repeat="country in ctrl.countries" ng-value= "{{ country }}" >
    {{ country.name }} ({{ country.prefix }})
  </md-option>
</md-select>

我的md解决方案选择多个。这是一个不错的css技巧,效果很好。

.option-hack {
  display: none;
}
md-option .option-hack {
  display: inline;
}
<md-input-container class="md-block">
  <label>Some Label</label>
  <md-select multiple
             ng-model="ctrl.array">
    <md-option ng-value="item" ng-repeat="item in ctrl.items" ng-selected="item.isOn">
      Always shown
      <span class="option-hack">Hidden on main</span>
    </md-option>
  </md-select>
</md-input-container>