I have an object as below. I have to display this as a drop-down:
var list = [{id:4,name:"abc"},{id:600,name:"def"},{id:200,name:"xyz"}]
In my controller I have a variable that carries a value. This value decided which of the above three items in the array will be selected by default in the drop-down:
$scope.object.setDefault = 600;
When I create a drop-down form item as below:
<select ng-model="object.setDefault" ng-options="r.name for r in list">
I face two problems:
the list is generated as
<option value="0">abc</option> <option value="1">def</option> <option value="2">xyz</option>
instead of
<option value="4">abc</option> <option value="600">def</option> <option value="200">xyz</option>
No option gets selected by default even though i have ng-model="object.setDefault"
$scope. payment = { type : 'Cash' } this will give you Cash as a default selected value. If i set on my controller, bydefault value is loading, but my select option change is not working. that is on change on option ng-if content is not loading.
Use ngValue and option element to set default value in dropdown list. You can set default value in dropdown list using ngValue directive and by hard-coding option element as shown in the example below. Let us set default text like “Select User” and disable it from user selecting that option.
Use the <select> element for this, which is a select box, also called drop down box, with option to list down items. Also, you can set the default value from the dropdown list of items in HTML forms. For that, add selected in the <option> tag for the value you want to preselect.
Hi Nishu, I guess your problem is AngularJS Dropdown automatically adds an Empty Value and you want to remove that blank value. The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. This happens to prevent accidental model selection.
Problem 1:
The generated HTML you're getting is normal. Apparently it's a feature of Angular to be able to use any kind of object as value for a select. Angular does the mapping between the HTML option-value and the value in the ng-model. Also see Umur's comment in this question: How do I set the value property in AngularJS' ng-options?
Problem 2:
Make sure you're using the following ng-options:
<select ng-model="object.item" ng-options="item.id as item.name for item in list" />
And put this in your controller to select a default value:
object.item = 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With