Home > Net >  How to add default option in select for AngularJS?
How to add default option in select for AngularJS?

Time:12-31

I don't know why this is not adding a default selected view:

I thought ng-init would make it have a default selected view.

How do I make the drop down box menu have a default selected value?

<select ng-init="selectedCar = Cars[0]" ng-model="selectedCar"  ng-required="true">
    <option value="" selected>Select a job title</option>
    <option ng-repeat="car in Cars" ng-value="car.firstname car.lastname">
        {{car.firstname}} {{car.lastname}}
    </option>
</select>

CodePudding user response:

You can try to initialize selectedCar in your controller rather ng-init.

Try the below code.

In your controller initialize it. For e.g: $scope.selectedCar = $scope.Cars[0];

And in the template:

<select ng-model="selectedCar"  ng-required="true">
    <option value="" selected>Select a job title</option>
    <option ng-repeat="car in Cars" ng-value="car.firstname car.lastname" ng-selected="selectedCar.id == car.id">
        {{car.firstname}} {{car.lastname}}
    </option>
</select>

Or

You can try using ng-options. Reference Another way by using ng-options

CodePudding user response:

You can set the default value for the select element by binding the ng-model with the variable you assigned with ng-init since ng-init doesn't assign the default value for the select and option components, but the default value to a variable in the scope. Try using selected in option to select the default value.

<select ng-init="selectedCar = Cars[0]" ng-model="selectedCar"  ng-required="true">
<option value="" selected>Select a job title</option>
<option ng-repeat="car in Cars" ng-value="car.firstname car.lastname" selected>
    {{car.firstname}} {{car.lastname}}
</option>

Or you can use ng-selected

<select ng-init="selectedCar = Cars[0]" ng-model="selectedCar"  ng-required="true">
<option value="" selected>Select a job title</option>
<option ng-repeat="car in Cars" ng-value="car.firstname car.lastname" ng-selected="$first">
    {{car.firstname}} {{car.lastname}}
</option>
  • Related