Search code examples
angularjsangular-filters

select box : display text 'error' if value not exist in array


I have a key value pair defined as below, which is being used for select using ng-options

 $scope.BucketEnum = [
    { display: 'Error', value: 0 },
    { display: '1', value: 1 },
    { display: '2', value: 2 },
    { display: '3', value: 3 },
    { display: '4', value: 4 },
    { display: '5', value: 5 },
    { display: 'Flows', value: 125 },
    { display: 'Recovery', value: 151 }
];

I am using this key value pair to display select box in ng-options

     <select ng-model="selectedBucket" ng-options="row.value as rows.display for row in BucketEnum" multiple="multiple" ></select>

now if I set ng-model i.e. $scope.selectedBucket = 10, I want to display the text Error. Is it possible to show value Error for all the values which are not there in $scope.BucketEnum array.

NOTE

I am looking at a more generic way to do this e.g a filter for doing this

SCENARIO

There is certain historical data in database, which has some garbage and some good data.

For each garbage value, i need to show the current garbage value as well as the valid values to select from, so for the end users to fix it.


Solution

  • Would this fit your needs ?

    jsfiddle

    app.filter('bootstrapValues', function(){
        return function(initial, baseBucket){
            var result = [];
            for(var i=0; i<initial.length; i++){
                var flag = false;
                for(var j=1; j<baseBucket.length; j++){ //from 1 or 0.. you call
                    if(initial[i] === baseBucket[j].value){
                        flag = true;
                        result.push(baseBucket[j]);
                        break; // if there are repeated elements
                    }
                }
                if(!flag)
                    result.push(baseBucket[0])
            }
            return result;
        };
    });
    

    Using it to start the selectedBucket, in your controller:

       // setting initials
            $scope.selectedBucket = $filter('bootstrapValues')(initialSet, $scope.bucketEnum);
    

    Does it help?

    Edit: Here is other jsfiddle with little modifications, if the value is not in the bucket it add the element to the list with Error display and as a selected value.