0

I am attempting to initialise a drop down selection with the first item in the list after it has been ordered by 'name' as shown:

<h2 class="presentation site is-input-header">Site</h2>
<div class="modal-select-element">
  <select ng-model="selected_site"
          ng-init="selected_site = availableSites()[0]"
          ng-options="site.name for site in availableSites() | orderBy:'name'">
  </select>
</div>

However the initial value is just a randomly selected site, not the first name on the list. Is there a way to show the first item in the sorted list?

1 Answer 1

2

Since you are already using a function availableSites() to populate your ng-options data, I would instead recommend sorting your data in the function instead of with ng-options. It will be more performant, and should avoid the issue you are coming across.

Controller:

$scope.availableSites() {
  var array = $scope.whateverMeansYouTookToGetYourDataFn();

  return array.sort(function(a,b){/* do your sorting or use lodash thats nice too */});
}

WHY?:

The reason you are seeing this side affect is because that availableSites()[0] is grabbing the first item of your unsorted array, meanwhile, then orderBy sorts them into whatever view order, not guaranteeing that availableSites()[0] is the first item after being sorted.

Example:

var unsortedArrayFromController = [
    {
      "name": "z"
    },
    {
      "name": "b"
    },
    {
      "name": "d"
    }
]

unsortedArrayFromController[0]

{name: z}

If ng-options sorts this object array, then the option with name 'z' will still be selected but now will be ordered differently (lets say last) therefore not neccessarily being the first item in the dropdown anymore.

Also:

On a side note. I would recommend storing selected_site = availableSites()[0] in the same controller that you are storing your availableSites() function. The ng-init directive is only to be used in a very specific case where you need to alias nested ng-repeat $index locals.

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.