Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I have searched Google and couldn't find anything on this.

I have this code.

<select ng-model="something Here" 

ng-options="option.value as option.name for option in options" >

</select>

With some data like this

options = [{ 

 name: 'Something Cool', 

 value: 'something-cool-value' 

}, { 

  name: 'Something Else', 

  value: 'something-else-value' 

}];

And the output is something like this.

<select ng-model="somethingHere" 

ng-options="option.value as option.name for option in options"  

  class="ng-pristine ng-valid"> 

  <option value="?" selected="selected"></option>

  <option value="0">Something Cool</option> 

  <option value="1">Something Else</option> 

</select>

How is it possible to set the first option in the data as the default value so you would get a result like this.

<select ng-model="somethingHere" ....> 

  <option value="0" selected="selected">Something Cool</option>  

  <option value="1">Something Else</option>

</select>

2 Answers

0 votes
by (106k points)
edited by

To have a default option in Angular.js select box.

Are you interested in learning Angularjs from the basics! Here's the right video for you on Angularjs provided by Intellipaat:

 you can simply use ng-init like this:-

<select ng-init="somethingHere = options[0]" 

    ng-model="somethingHere" 

    ng-options="option.name for option in options">

</select>

Looking for a comprehensive Angular Course? Enroll now! 

0 votes
ago by (1.9k points)

 You can use ng-init like this  as per the code demonstration:- 

<select ng-init="somethingHere = options[0]" 

        ng-model="somethingHere" 

        ng-options="option.name for option in options">

</select>

ng-init="somethingHere = options[0]": This will set here the somethingHere variable to the first object in the options array when the component gets loaded. Thus, the first option becomes the default selected value in the dropdown.

ng-model="somethingHere": This binds the selected value of the dropdown to the somethingHere variable, which you can then access in your AngularJS controller.

ng-options="option.name for option in options": It will create dropdown options which depend on the name property of every object in the options array.

Output:

On running this, it initializes the dropdown to "Something Cool" automatically (as the first option), which you'll notice has assigned the value somethingHere. That's short, sweet, and quite effective in defaulting a value without needing a controller to do more.

Related questions

0 votes
1 answer
asked Aug 29, 2019 in Web Technology by Sammy (47.6k points)
+2 votes
1 answer
+2 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...