0

I am creating a simple select directive with angularjs.

My problem is that the order of the options in the select directive are out of order.

The directive gives numeric options up to 100. I first build an array using a loop when my controller is first created and add it to the model.

 var init2 = 1;
 var percentageAmount = [];
 while(init2 != 100) {
     var current = {value:init2, id:init2};
     percentageAmount[init2] = current;
     init2++;
 }
 $scope.percentageAmounts = percentageAmount;
 $scope.percentageAmount = 1;

I then bind to that array on the template.

Percentage Amount:

<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>

and find that the options are out of order in the dom. It looks like it's grouping it all alphabetically (with numbers being highest).

enter image description here

I find this confusing because I also have created arrays of non numerically based values and bound those to select directives and the options that show up in the select directive in the document object model always are in the same order as the ordering in the array which the select directive is bound

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>

Here is the array building logic for that last select directive

$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"}];

enter image description here

I've experimented with changing all of the array values to integer based strings (on the id, the value and both)

Has anyone ran across this and found a solution? I would be much obliged if you can help.

3

1 Answer 1

2

This happens because you "treat" the array as an object, so the numeric indices are interpreted as string property-names of an object.

Angular thinks its an object, because of the form of ngOptions that you use:

... for (key, value) in ...

In order for Angular to know it is an array, you can change it like this:

<select ... ng-options="amount.id as amount.value for amount in percentageAmounts">
</select>

See, also, this short demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.