ngOptions

ngOptions 是一个指令,它简化了 html 下拉框的创建,以便从将存储在模型中的数组中选择项目。ngOptions 属性用于使用通过评估 ngOptions 理解表达式获得的数组或对象动态生成 <select> 元素的 <option> 元素列表。

使用 ng-options,标记可以简化为一个选择标记,指令将创建相同的选择:

<select ng-model="selectedFruitNgOptions" 
        ng-options="curFruit as curFruit.label for curFruit in fruit">
</select>

有使用 ng-repeat 创建 select 选项的另一种方法,但不推荐使用 ng-repeat,因为它主要用于通用目的,例如,forEach 只是为了循环。而 ng-options 专门用于创建 select 标签选项。

上面使用 ng-repeat 的例子是

<select ng-model="selectedFruit">
    <option ng-repeat="curFruit in fruit" value="{{curFruit}}">
        {{curFruit.label}}
    </option>
</select>

完整的例子

让我们详细看一下上面的例子,里面还有一些变化。

示例的数据模型:

$scope.fruit = [
    { label: "Apples", value: 4, id: 2 },
    { label: "Oranges", value: 2, id: 1 },
    { label: "Limes", value: 4, id: 4 },
    { label: "Lemons", value: 5, id: 3 }
];
<!-- label for value in array -->
<select ng-options="f.label for f in fruit" ng-model="selectedFruit"></select>

选择时生成的选项标签:

 <option value="{ label: "Apples", value: 4, id: 2 }"> Apples </option>

功效:

f.label 将是 <option> 的标签,该值将包含整个对象。

完整的例子

<!-- select as label for value in array -->
<select ng-options="f.value as f.label for f in fruit" ng-model="selectedFruit"></select>

选择时生成的选项标签:

 <option value="4"> Apples </option>

功效:

f.value(4)将是这种情况下的值,而标签仍然是相同的。

完整的例子

<!-- label group by group for value in array -->
<select ng-options="f.label group by f.value for f in fruit" ng-model="selectedFruit"></select>

选择时生成的选项标签:

<option value="{ label: "Apples", value: 4, id: 2 }"> Apples </option>

功效:

选项将根据 value 进行分组。具有相同 value 的选项将属于一个类别

完整的例子

<!-- label disable when disable for value in array -->
<select ng-options="f.label disable when f.value == 4 for f in fruit" ng-model="selectedFruit"></select>

选择时生成的选项标签:

<option disabled="" value="{ label: "Apples", value: 4, id: 2 }"> Apples </option>

功效:

由于条件 disable when f.value==4苹果酸橙将被禁用(无法选择)。value=4 的所有选项均应禁用

完整的例子

<!-- label group by group for value in array track by trackexpr -->
<select ng-options="f.value as f.label group by f.value for f in fruit track by f.id" ng-model="selectedFruit"></select>

选择时生成的选项标签:

<option value="4"> Apples </option>

功效:

使用 trackBy 时没有视觉上的变化,但 Angular 会通过 id 而不是参考来检测变化,而这最常见的是更好的解决方案。

完整的例子

<!-- label for value in array | orderBy:orderexpr track by trackexpr -->
<select ng-options="f.label for f in fruit | orderBy:'id' track by f.id" ng-model="selectedFruit"></select>

选择时生成的选项标签:

<option disabled="" value="{ label: "Apples", value: 4, id: 2 }"> Apples </option>

功效:

orderBy 是一个 AngularJS 标准过滤器,它按升序排列选项(默认情况下),因此其中的 Oranges 将显示为 1st,因为它的 id = 1。

完整的例子

所有 <select>ng-options 必须连接 ng-model