Marco
Marco

Reputation: 1652

AngularJS: How to obtain the filtered array of ng-options

I have a select like this:

<select ng-model="myType"
ng-options="type in types | filter:compatibleTypes">

compatibleTypes is defined as a function in $scope by controller:

$scope.compatibleTypes = function(item) {
 //Returns true or false
 //depending on another model
}

In the controller I need to know the first filtered element (if any) of array 'type'. Or more precisely, I have to set the value of the model 'myType' with the first element of the filtered list, when it changes.

Upvotes: 0

Views: 48

Answers (2)

Danilo Valente
Danilo Valente

Reputation: 11342

filter is an Angular native filter. That means it can be injected to many places, including your controller:

var myController = ['$scope', 'filterFilter', function ($scope, filterFilter) {
    $scope.compatibleTypes = function(item) {
        //Returns true or false
        //depending on another model
    }
    $scope.filteredResults = filterFilter($scope.types, $scope.compatibleTypes);
}];

Upvotes: 1

Jason van der Zeeuw
Jason van der Zeeuw

Reputation: 923

Inject $filter to your controller

function myCtrl($scope, $filter)
{
}

Then you can just use the filter in your controller and you don't have to use it in your HTML anymore!

    $scope.filteredTypes = $filter('filter')(types, $scope.compatibleTypes);

In your HTML you can use ng-options="type in filteredTypes" And in your controller

$scope.filteredTypes[0] 

to get the first one!

Upvotes: 1

Related Questions