我正在使用angularjs创建一个简单的select指令。
我的问题是select指令中选项的顺序是乱序的。
该指令提供最多100个数字选项。 我首先在我的控制器创建时使用循环构建一个数组并将其添加到模型中。
var init2 = 1;
var percentageAmount = [];
while(init2 != 100) {
var current = {value:init2, id:init2};
percentageAmount[init2] = current;
init2++;
}
$scope.percentageAmounts = percentageAmount;
$scope.percentageAmount = 1;
然后我绑定到模板上的那个数组。
百分比金额:
<select ng-model="$parent.percentageAmount" name="percentage-amount" id="percentage-amount" ng-options="value.id as value.value for (key,value) in $parent.percentageAmounts" required>
</select>
并发现dom中的选项无序。它看起来像是按字母顺序对它进行分组(数字最高)。
我发现这令人困惑,因为我还创建了非数字值的数组并将它们绑定到选择指令,并且文档对象模型中的select指令中显示的选项总是与订单中的顺序相同。 select指令绑定的数组
Category:
<select ng-model="couponCategory" name="coupon-category" id="coupon-category" ng-options="value.id as value.value for (key,value) in couponCategories" required>
</select>
这是最后一个select指令的数组构建逻辑
$scope.couponCategories = [{value:"Whole Order", id:"Whole Order"},{value:"Per Item", id:"Per Item"},{value:"Per Item Quantity", id:"Per Item Quantity"},{value:"In A Category", id:"In A Category"}];
我已尝试将所有数组值更改为基于整数的字符串(在id,值和两者上)
是否有人遇到此问题并找到解决方案?如果你能提供帮助,我将非常感激。
答案 0 :(得分:2)
这是因为你&#34;治疗&#34;数组作为对象,因此数字索引被解释为对象的字符串属性名称。
Angular认为它是一个对象,因为你使用ngOptions
的形式:
... for (key, value) in ...
为了让Angular知道它是一个数组,你可以改变它:
<select ... ng-options="amount.id as amount.value for amount in percentageAmounts">
</select>
另请参阅此 short demo 。