Set Default Value In Select When The Ng-model Is Null
Solution 1:
Try this:
<select ng-init="item.carType = item.carType || 'none'" ng-model="item.carType">
<option value="none">None</option>
<option value="manual">Manual</option>
<option value="auto">Auto</option>
</select>
That said, per the docs, this is probably a misuse of ngInit
. The proper way to do this would be to initialize your model with sane values in the controller (or service, if that's where it came from).
Solution 2:
H i ,
My thoughts are it is best to do this in the app rather than the template.
if(typeof $scope.item.carType==="undefined") {
$scope.item.carType="none";
}
or simply setting the value
$scope.item.carType="none";
before it is updated with whatever you are using to set the value : -
$scope.item.carType="none";
$scope.item.carType=someasyncfunctionthatmighttakeawhileandthetemplateisrenderedbeforeitarrives();
Solution 3:
You can solve using a value in ng-init
<select ng-init="item.carType='none'" ng-model="item.carType">
<option value="none">None</option>
<option value="manual">Manual</option>
<option value="auto">Auto</option>
</select>
Solution 4:
What I would suggest you to do is this.
Make a function in your controller and check if $scope.item.carType == undefined
assign a default value.
$scope.setDefaultValueForCarType = function () {
if($scope.item.carType == undefined) {
$scope.item.carType = "none";
}
}
This will work too.
<select ng-init="item.carType='none'" ng-model="item.carType">
Solution 5:
Often happens that your ng-model="item.carType"
doesn't match any of the select option keys because of the wrong case.
For example: item.cartType
is "Manual"
but in the options you have an option <option value="manual">Manual</option>
in this case it won't work and in the console output you'll see something like this: <option value="? string:Manual ?"></option>
So, either correct your data model or your select option value:
<option value="Manual">Manual</option>
Post a Comment for "Set Default Value In Select When The Ng-model Is Null"