【问题标题】:check option select ng-repeat检查选项选择 ng-repeat
【发布时间】:2015-11-26 11:02:34
【问题描述】:

我需要检查 ng-repeat 中值数组的长度,取决于此,我必须添加 <option><optgroup>

ng-repeat 看起来像这样:

<select name="countries">
    <option ng-repeat="country in countries">{{ country.country_name }}</option>
</select>

“国家”是一个对象数组,如下所示:

[
    {
       country_name: "Argentina"
       language: Array[2]
       locale_code: "AR"
    },
    {
       country_name: "Austria"
       language: Array[1]
       locale_code: "AR"
    },
    ....
    ....
]

代码应该是这样的,但是是有角度的:

<select name="countries">
    for (var i; i < countries.length; i++) {
      if (countries[i].languages.length > 1) {
      <optgroup value="{{ i }}" label="{{ country.country_name }}">
         for (var j; j < countries[i].languages.length; i++) { 
         <option value="{{ countries[i].languages[j].value }}">{{ countries[i].languages[j].name }}</option>
         }
      </optgroup>
      } else {
      <option value="{{ countries[i].languages[0].value }}">{{ countries[i].languages[0].name }}</option>
      }
    }
</select>

任何线索如何用角度模板做到这一点?

提前致谢

【问题讨论】:

  • 你可以使用 ng-if="country.languages.length==1" 和 ng-if="country.languages.length>1" 就像你在非角模板
  • 这样我必须做两次 ng-repeat,一个用于 option,另一个用于 optgroup……它都会被复制,对吗?
  • 如果是做分组选项,你也可以看看可选选项中的docs.angularjs.org/api/ng/directive/ngOptionsgroupBy

标签: javascript angularjs select angularjs-ng-repeat


【解决方案1】:

这个问题很棘手,因为你只能在&lt;select&gt; 中使用&lt;option&gt;&lt;optgroup&gt;

实现此目的的一种方法是将两个单独的ng-repeats 与ng-if 结合使用,但这会打乱值的顺序。

最合适的方式是ng-repeat-start/ng-repeat-endng-if结合使用:

<select ng-model="selectedLanguage">
  <optgroup ng-repeat-start="country in countries" 
            ng-if="country.language.length > 1" 
            label="{{country.country_name}}">
    <option ng-repeat="lang in country.language" 
            value="{{lang}}">{{lang}}</option>
  </optgroup>
  <option ng-repeat-end 
          ng-if="country.language.length === 1" 
          value="{{country.language[0]}}">
    {{country.language[0]}}
  </option>
</select>

Demo

【讨论】:

  • 我正在我的代码中检查它,感谢您的回复。我会告诉你的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
  • 2018-04-29
  • 1970-01-01
  • 1970-01-01
  • 2017-08-05
  • 1970-01-01
相关资源
最近更新 更多