0

I have a lot of select boxes in my application, being generated by lists of data and assigned to various ng-models.

I want to set the ng-model value to the first available option (respecting filters) of all select inputs globally in the app.

So for example a select input like this:

<select ng-model="entry.employee">
  <option ng-value="employee.name" ng-repeat="employee in employees | filter:active">{{employee.name}}</option>
</select>

The entry.employee ng-model defaults to null, I need every select box to never be null but always select the first valid option of a select input by default.

It needs to be global as well and be generic enough to work with any type of select input.

Here is the data:

$scope.employees= [
        {'name':'Bill'},
        {'name':'Frank'},
        {'name':'Ted'},
    ];
Jordash
  • 2,926
  • 8
  • 38
  • 77

1 Answers1

0

Instead of using ng-repeat on option elements use directly ng-option on select tag.

for example

<select class="form-control" ng-options="item.name for item in employees track by item.id" ng-model="selectedItem"></select>

in you controller use:

$scope.selectedItem=$scope.employees[0];

your object would be like:

$scope.employees= [
    {id:'1','name':'Bill'},
    {id:'2','name':'Frank'},
    {id:'3','name':'Ted'},
];

In this case let you select tags be 'n' numbers but whenever you want you ng-model to be the first one just initialize it with the first element in your Object. Also there is a good thing using ng-option is whenever you want to change the value of the select element at runtime you just need to update the selectedItem element.

Hope this resolves your query

Wasimakram Mulla
  • 511
  • 7
  • 24