Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs: ng-options group by

I have this one level tree situation:

<select ng-model="tipost"          ng-options="tip.DESC group by tip.TIPIS for tip in tipall"><br> </select> 



where the json is:

[   {"ID":"1", "IDPARENT":"0", "TIPIS":"", "DESC":"GroupName1"},   {"ID":"2", "IDPARENT":"1", "TIPIS":"GroupName1", "DESC":"CHILDNAME1"},   {"ID":"3", "IDPARENT":"0", "TIPIS":"", "DESC":"GroupName2"} ] 


the problem is that this creates the optgroups with their children but repeats the roots too:

- GroupName1 - GroupName2 [ GroupName1 ] - CHILDNAME1 [ GroupName2 ] 


i want to produce:

[ GroupName1 ] - CHILDNAME1 [ GroupName2 ] 


like image 797
daniel Avatar asked Sep 04 '13 13:09

daniel


People also ask

How to use ng-options in Angular?

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.

How do I filter with Ng-options?

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.

What is ngOptions?

The ngOptions attribute can be used to dynamically generate a list of <option> elements for the <select> element using the array or object obtained by evaluating the ngOptions comprehension expression.

How do I set default value in ng-options?

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. Essentially when you define the $scope property your select will bind to assign it the default value from your data array.


2 Answers

The grouping doesn't quite work like that, if you change your json to something like this:

[  {"ID":"1", "TIPIS":"GroupName1", "DESC":"name"},  {"ID":"2", "TIPIS":"GroupName1", "DESC":"name1"},  {"ID":"3", "TIPIS":"GroupName2", "DESC":"name2"},  {"ID":"4", "TIPIS":"GroupName1", "DESC":"name3"}, ] 

Then you'll get the grouping the way you want

jsFiddle: http://jsfiddle.net/rtCP3/182/

like image 134
Mathew Berg Avatar answered Sep 19 '22 21:09

Mathew Berg


The simple drop down that can display items with and without groups, and also you can set some items as disabled: Here is plunk: https://plnkr.co/edit/uhsn4lmzssi6rrijPEAp?p=preview

 <select ng-model="ddl.selected"     ng-options="item.id as item.text group by item.groupName disable when item.enabled===false for item in ddl.items"></select> 
like image 32
Xalisys Avatar answered Sep 21 '22 21:09

Xalisys