Search code examples
angularjsangularjs-filterangularjs-ng-options

Select first value from select box by default - AngularJS


I have two select boxes. The second select box populates from first select box.

I have applied a filter for the second select box to populate as per the options selected in first select box. The second select box populates from an array var outputformats = [];

This is my code

HTML

<select name="reporttype"id="reporttype" 
        ng-init="reporttype='1115'" 
        ng-model="reporttype">
    <option value="1115">Previous Day Composite Report</option>
    <option value="1114">ACH Receive</option>
</select>


<select name="outputformat" id="outputformat" 
        ng-model="outputformat" 
        ng-options="format for format in outputformats | outputformatfilter: reporttype:this">      
</select> Value : {{outputformat}}

Filter

angular.module('myApp.outputformatfilter',[])
    .filter('outputformatfilter', function () {
        return function (input,selectedreport,scope) {

            var outputFormatReport  = {"1115":"HTML,PDF","1114":"CSV,EXCEL"};
            var outputformats = outputFormatReport[selectedreport].split(',');

            return outputformats;
        };
    });

Now what I want is whenever the options in second select box changes, its first option should be selected by default, that is the first option from the array should be selected by default.

UPDATE:

Updated fiddle, added ng-if= reporttype !== '' to second select box

FIDDLE


Solution

  • On your controller, watch the filtered options and act on that:

    function myController ($scope) {
        // watch the filtered output formats
        $scope.$watchCollection("filteredOutputFormats", function(val) {
            // select the first one when it changes
            $scope.outputformat = val[0];
        });
    }
    

    Make sure you assign the filtered results to a $scope variable:

    <select name="outputformat" id="outputformat" 
            ng-model="outputformat" 
            ng-options="format for format in filteredOutputFormats = (outputformats | outputformatfilter: reporttype:this)">        
    </select>
    

    JSFIDDLE