Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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


Solution 2:

How about using a filter? Like

    <select ng-options="value as value for value in (values_array | yourFilter)"></select>

yourFilter might be something in the lines of this answer:

.filter('inArray', function($filter){
    return function(list, arrayFilter, element){
        if(arrayFilter){
            return $filter("filter")(list, function(listItem){
                return arrayFilter.indexOf(listItem[element]) != -1;
            }); 
        }
    };
});

Solution 3:

Just use a function that will return the filtered values. You may also use a separate filter but a function should be much easier in this case

 <select name="mySelect" id="mySelect" ng-model="mySelectmodel" ng-options="value as value for value in filteredValues(values_array)">

$scope.filteredValues = function () {
    return $scope.values_array.filter(function (val) {
        return $scope.skip_array.indexOf(val) === -1;
        });
    };

Here is the full working example

FULL EXAMPLE


Solution 4:

Html

<select ng-modal="yourmodalname" ng-options="x.id as x.name for x in arraylistofvalue | filter : selectedvalues"></select

angular controller

 $scope.selectedvalues = function(value , index , array ){
     if (value.id == 1){
            return $scope.arraylistofvalue.indexOf(value);
         }

      }

array list

$scope.arraylistofvalue = [{id : 1 ,name : 'value1'}{id : 2 ,name : 'value2'}]

Post a Comment for "Angular Ng-options With Conditional On Value In Simple Array Of Strings"