How to select first select option after filtering in Angular
angularjs
Solution
change
%select{'ng-model' => 'device', 'ng-options' => 'device.serial_number for device in devices | filter:search'}
to
%select{'ng-model' => 'device', 'ng-options' => 'device.serial_number for device in filtered_devices=(devices | filter:search)'}
and you will have filtered_devices in your scope to do with what ever you wish specifically you can watch it and set the selected device when it changes
$scope.$watch('filtered_devices', function(value){
if (filtered_devices) {
$scope.device = filtered_devices[0];
}
}, true);
so you don't have to filter again...
UPDATE:
After working with the model I suggested I discovered that is probably a bad idea to have a filter expression as the source for ng-options. I assume that the reason is that each time the filter is evaluated it returns a new collection and hence the diget cycle concludes that its is dirty and needs rebinding or whatever.
I am now using a different pattern in which I have a `filtered_items` collection in my `$scope` and I am updating it via "ng-change" on the filter input. so the `filtered_items` to which ng-options is bound does not change unless it actually needs to change...
Problem
I have a `select` with filter. After filtering Angular loses the selected item from the list, and add first empty `option` item. What should be done to make the first available option selected instead? Here is the markup: ``` %select{'ng-model' => 'search.device_type_id', 'ng-options' => 'type.id as type.product_name for type in device_types'} %select{'ng-model' => 'device', 'ng-options' => 'device.serial_number for device in devices | filter:search'} ```