deagleshot
deagleshot

Reputation: 215

How to add default option in select for AngularJS?

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" class="form-control" 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>

Upvotes: 1

Views: 57

Answers (2)

Apocryphon
Apocryphon

Reputation: 45

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" class="form-control" 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" class="form-control" 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>

Upvotes: 1

Amit Vishwakarma
Amit Vishwakarma

Reputation: 316

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" class="form-control" 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

Upvotes: 1

Related Questions