Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value in select when the ng-model is null

I'm new to angular and i'm trying to set a default state to select when my ng-model is null. Basically I want to set it to 'None' if the model is empty. I tried the below code but it's not working.

<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>
like image 508
user1184100 Avatar asked Dec 31 '13 15:12

user1184100


People also ask

How do I set default selected value in ng-options?

Use ng-init to set default value for ng-options . Save this answer. Show activity on this post. In my opinion the correct way to set a default value is to simply pre-fill your ng-model property with the value selected from your ng-options , angular does the rest.

What is ng-options?

Definition and Usage. The ng-options directive fills a <select> element with <options>. The ng-options directive uses an array to fill the dropdown list. In many cases it would be easier to use the ng-repeat directive, but you have more flexibility when using the ng-options directive.


2 Answers

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).

like image 113
Tautologistics Avatar answered Sep 22 '22 09:09

Tautologistics


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();
like image 30
Rob Sedgwick Avatar answered Sep 26 '22 09:09

Rob Sedgwick