Search code examples
angularjsdrop-down-menudefaultangular-ngmodelng-options

Selecting default value for ng-options in Angular


I have two dropdowns, one is dependent on the other. I originally had my code using ng-repeat but read that it is more efficient to use ng-options. However, in switching over, I can't use ng-selected for the default any longer.

I've looked at different methods of setting the default option in ng-options but they use either <option value="">Select Something Here</option> for a customized option or selecting straight from the dataset. However my value will be changing.

Here is a working plunker using ng-repeat:

http://plnkr.co/edit/Ie4VDDlrwSUSqIq7laoa?p=preview

Here is a plunker missing the default using ng-option:

http://plnkr.co/edit/TGoWTMqOuJnWKNTUARWI?p=preview

The default value should be $scope.defnum , which is taken from a different dataset than the values in my dropdown, so I want to have the default DefCom = defnum. I've tried doing this using ng-init by assigning an original variable in the controller:

 $scope.defcom = 4;
 var original_defcom = $scope.defcom;

and using ng-init="original_defcom" in the template.

and in ng-model, even wrapping it in an <option> tag


Solution

  • Do this in the ng-options

    <select ng-model="defcom"
        ng-options="opt.DefCom as opt.DefCom for opt in acct_info | filter:{Req:'MUST'}:true" >
    </select>
    

    Then, you have to change de $scope.defcom type to match the array. In the plunker the variable is a Number and the array is full of Strings. You have to change one of them. If I where you, I'd change the type of the properties in the objects in the array. The ng-options parses the numbers automatically.

    This is an version of your plunker afters a few changes:

    http://plnkr.co/edit/tIeDEC8MxfcvnRrc0Njh?p=preview