schuimer schuimer - 2 months ago 11
AngularJS Question

Angular ng-options with conditional on value in simple array of strings

I have two array shaped like this:

$scope.values_array = ['string1', 'string2', 'string3', 'string4'];
$scope.skip_array = ['string2', 'string3'];


and I try to use ng-options like this:

<select ng-options="value as value for value in values_array && skip_array.indexOf(value) === -1"></select>


This doesn't produce an error but nothing shows up in the dropdown anymore. Without the "&& skip_array.indexOf(value)" it shows all the options in values_array.

Answer

html:

<select ng-model="selectedValue" ng-options="value as value for value in values_array | filter:skipValues"></select>

controller:

$scope.skipValues = function(value, index, array) {
    return $scope.skip_array.indexOf(value) === -1;
};
$scope.values_array = ['string1', 'string2', 'string3', 'string4'];
$scope.skip_array = ['string2', 'string3'];

jsfiddle

UDPATE:

If you want to pass an extra parameter to the filter function

html:

<select ng-model="selectedValue" ng-options="value as value for value in values_array | filter:skipValues(1)"></select>

controller:

$scope.skipValues = function(anInt) {
    return function(value, index, array) {
        return $scope.skip_array.indexOf(value) === -1 && anInt > 0;
    }
};
$scope.values_array = ['string1', 'string2', 'string3', 'string4'];
$scope.skip_array = ['string2', 'string3'];

jsfiddle

Comments