1

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>
2
  • can u add your TS code? Commented Dec 30, 2022 at 7:40
  • ng-model should initialized with value of option. just rewrite it as, <select ng-init="selectedCar = Cars[0].firstname+' '+Cars[0].firstname" <option value="" selected>Select a job title</option> <option ng-repeat="car in Cars" ng-value="car.firstname car.lastname"> {{car.firstname}} {{car.lastname}} </select> Commented Dec 30, 2022 at 7:47

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.