angularjs ui-select-choices dropdown aphabetical order depending on the input given

Swap picture Swap · Aug 17, 2016 · Viewed 11k times · Source

I'm using https://github.com/angular-ui/ui-select for the website I'm working on. Currently the code is as follows:

       <ui-select ng-model="model.states">
         <ui-select-match placeholder="State">
           {{$item.Name}}
         </ui-select-match>
         <ui-select-choices repeat="item.Code as item in statesArray | filter:$select.search">
            {{item.Name}}
         </ui-select-choices>
      </ui-select>

When I type anything in the input field, for example "a", ui-select-choices shows all the fields containing "a" (by default). What I want to do is, I want to show all the states starting with "a" only. If nothing is typed in the input box, then show all the fields in alphabetical order. Can someone please propose a solution? I saw few other posts but no one has answered this question yet. Thanks in advance.

Example

Here's an example, suppose states array has states like California, Connecticut, Alaska, Arizona, New York.

If nothing is typed in the input field, dropdown should show Alaska, Arizona, California, Connecticut, New York (which can be achieved using orderBy filter).

If user types "a" in the input field, dropdown should show Alaska, Arizona and no other fields as Alaska and Arizona are only fields starting with "a". If user types "c", dropdown should show California, Connecticut. If user types "ca", dropdown should show California only as it only matches the input string given.

Answer

BrokenRobot picture BrokenRobot · Aug 17, 2016

If I understand you correctly, I think all you need to do is add

| orderBy:'Name'

<ui-select-choices repeat="item.Code as item in statesArray | filter:$select.search | orderBy:'Name'">
{{item.Name}}
</ui-select-choices>

Check out orderBy for more information