简体   繁体   中英

Creating a Grouped Select in Ember.js

It's relatively easy to create a select in Ember.js using Ember.Select .

The question is, how do I make this into a grouped select, using an optgroup. I don't think this is built in, but I'm guessing it's possible with some modifications to the template.

This is natively supported by Ember now, but there are a few gotchas. In 1.4.0, the following solution works...

Here's the example data:

foos: Ember.A([{value: 'foo', label: 'Foo', group: 'Foos'}, {value: 'bar', label: 'Bar', group: 'Bars'}, {value: 'bar2', label: 'Bar2', group: 'Bars'}, {value: 'foo2', label: 'Foo2', group: 'Foos'}])

Here's the view helper:

{{view Ember.Select content=controller.foos optionLabelPath='content.label' optionValuePath='content.value' optionGroupPath='group'}}

If, you just do the above you will get a select list that looks like this:

在此输入图像描述

The only way I could get around this was to sort the array first by the grouped field:

foos: Ember.A([{value: 'foo', label: 'Foo', group: 'Foos'}, {value: 'bar', label: 'Bar', group: 'Bars'}, {value: 'bar2', label: 'Bar2', group: 'Bars'}, {value: 'foo2', label: 'Foo2', group: 'Foos'}]).sortBy("group")

在此输入图像描述

Here's the solution that I came up with. https://gist.github.com/3297425

I had to make two collections. One grouped and the other just content so that the proper option can be selected.

groupedServiceCodes = [Ember.Object.create({label: 'Label for optgroup', content: Ember.A()}), …]

And then flatten the content from groupedServiceCodes down to maintain order for the select:

flattenedServiceCodes = [].concat(object.get('content'), …)

This is a bit of a hack, and I think Ember is wanting for a better solution, but this works for me. I would love to hear thoughts on improving this.

The answers here are a bit outdated. Ember now supports grouping of stuff. Imagine you have:

App.SomeController = Ember.Controller.extend({
  content: [{value: 'foo', label: 'Foo', group: 'Foos'}, {value: 'bar', label: 'Bar', group: 'Bars'}]
})

You can then do

Ember.Select contentBinding='content' optionLabelPath='content.label' optionValuePath='content.value' optionGroupPath='group'

Notice that optionGroupPath does not do content.path, just path

Ember.Select does not support optgroups, but you can extend Ember.Select to do so by providing a new template for it and a new template for options. I've done this to support chosen.js selects within Ember.

Ember now supports this out of the box. Refer to this git pull request https://github.com/emberjs/ember.js/pull/2465

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM