Search code examples
angularjsng-options

Using ng-option with sorting and custom text


I have the following ng-repeat:

<select class="action-dropdown fade" ng-model="item_value">
    <option value="" disabled>Choose an Step</option>
    <option ng-repeat="step in steps | orderBy:'+step_number'" ng-if="step.step_number >= active_step" value="{{$index}}">Step {{step.step_number}}</option>
</select>

I am attempting to change this to an ng-option because the following option is popping up and I think this might fix the issue:

<option value="? string:5 ?"></option>

I'm trying to wrap my head around how to include my ng-if statement with the ng-option and to use the word Step $index when displaying the option.

The comprehension expressions are just blowing my mind and I was wondering if anyone could help me out.

This is what I have so far:

<select class="action-dropdown fade" ng-model="item_value" ng-options="$index as step.step_number for step in steps" required>
    <option value="" disabled>Choose a Step</option>
</select>

Solution

  • look the snipped as I've commented

    I think that the best way (cleaner way) is populate the steps list on change active_step. To access the index you can use the (key,value) syntax

    select as label for (key , value) in object
    

    Doc: https://docs.angularjs.org/api/ng/directive/ngOptions

    angular.module('app', [])
    .controller('DefaultController', function () {
        this.item_value = null;
        this.steps = [ 
            { step_number: 5 }, 
            { step_number: 2 },  
            { step_number: 6 },
            { step_number: 3 },
        	{ step_number: 1 }, 
            { step_number: 4 },
        ]
      });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app="app">
      <div data-ng-controller="DefaultController as ctrl">
        <select ng-model="ctrl.item_value" ng-options="step as 'Step ' + index for (index, step) in ctrl.steps | orderBy:'+step_number'" required>
        <option value="" disabled>Choose a Step</option>
    </select>
        
        Selected: {{ ctrl.item_value }}
      </div>
    </div>