Glen Solsberry
Glen Solsberry

Reputation: 12320

Default value with ng-options after filter

I have a <select> box with options driven from a filter, based on the value of another field in the model (another <select> field). If, after filtering the list, there's only one option to display, I want to make it the selected option. ng-init seems like a starting point, but it's also recommended by the Angular team as something to not use.

SELECT:

 <select
    tabindex="5"
    class="form-control"
    ng-model="vm.transaction.um"
    ng-options="um.name for um in vm.ums | measuresForItem:vm.transaction.item">
 </select>

Upvotes: 1

Views: 915

Answers (2)

Vasily Liaskovsky
Vasily Liaskovsky

Reputation: 2528

Basically what you want to do is to change some model value (vm.transaction.um) based on some other model value (filtered vm.ums). There is $watch() function that does exactly this thing. Try

$scope.$watch('(vm.ums | measuresForItem:vm.transaction.item).length', function(newVal) {
    if (newVal == 1)
        $scope.vm.transaction.um = (<get filtered result here>)[0].name;
});

Actually ng-init is not that bad for such sort of tasks, but it executes only once, and it might be not suitable for dynamic filters or any kind of deferring.

Upvotes: 2

R. Salisbury
R. Salisbury

Reputation: 2006

Just set vm.transaction.um (the member you assigned to ng-model) in your controller:

if(this.vm.ums.length === 1) {
    this.vm.transaction.um = this.vm.ums[0];
}

Upvotes: 0

Related Questions