I have the following json object:
$scope.values = [
{
"id": 2,
"code": "Code 1",
"name": "Sample 1"
},
{
"id": 4,
"code": "Code 2",
"name": "Sample 2"
},
{
"id": 7,
"code": "Code 3",
"name": "Sample 3"
}
];
In select tag, I have this:
<select name="c_id" ng-options="c.id as c.code for c in values"></select>
The generated select options is:
Code 1
Code 2
Code 3
Is there any way to format the text in the options like the following?
Code 1 -- Sample 1
Code 2 -- Sample 2
Code 3 -- Sample 3
Or I'll just have to prepare the values before attaching them to the model? Any help is appreciated. Thank you.
In order to load the select with default value you can use ng-options. A scope variable need to be set in the controller and that variable is assigned as ng-model in HTML's select tag.
In AngularJS when you are using ng-options, you can filter out the options by calling a custom function you have in the controller. Let's say you have following set of employees and when you display all these employees inside HTML select using ng-options, you can see all the employees in a dropdown.
The ng-options Directive in AngularJS is used to build and bind HTML elements with options to a model property. It is used to specify <options> in a <select> list. It is designed specifically to populate the items on a dropdown list. This directive implements an array, in order to fill the dropdown list.
Overview. HTML select element with AngularJS data-binding. The select directive is used together with ngModel to provide data-binding between the scope and the <select> control (including setting default values). It also handles dynamic <option> elements, which can be added using the ngRepeat or ngOptions directives.
You can do it by using this syntax:
ng-options="c.id as (c.code + ' -- '+ c.name) for c in values"
Example: http://jsfiddle.net/cherniv/6EkL7/1/
Or someone may like next syntax:
ng-options="c.id as [c.code,c.name].join(' -- ') for c in values"
Example: http://jsfiddle.net/cherniv/6EkL7/2/
But in some cases there is rationality in using a Filter , like:
app.filter("formatter",function(){
return function(item){
return item.code+ " -- " + item.name;
}
})
And: ng-options="c.id as c|formatter for c in values"
Example: http://jsfiddle.net/cherniv/K8572/
Sure, you can achieve that by invoke ng-repeat
for option
,
HTML
<select>
<option ng-repeat="v in values" value="{{v.id}}">
{{v.code}} -- {{v.name}}
</option>
</select>
JS
the same
Demo Fiddle
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