文档说使用model.bind 选择多个。所以select应该是这样的:
<select multiple='multiple' value.two-way="selectedThings" style="width: 100%">
<option repeat.for="thing of things" model.bind="thing">${thing.name}</option>
</select>
但是,selectedThings 中的更改似乎没有反映在视图上。我相信这是因为 aurelia 在内部设置绑定值的方式。我们应该等待团队的回答来了解为什么会发生这种情况。同时,我可以使用对selectedThings 进行脏检查的getter 属性来解决这个问题。像这样:
get myThings() {
return this.selectedThings.map(thing => thing.name).join(',');
//or just return this.selectedThings
}
运行示例:https://gist.run/?id=5a9c5cda449bfe3789a58122372a0a20
编辑
如果您想使用 select2,您可以操作 select2 自定义属性中的所有内容。像这样:
自定义属性
import {inject} from 'aurelia-dependency-injection';
import {customAttribute} from 'aurelia-templating';
import {DOM} from 'aurelia-pal';
import {TaskQueue} from 'aurelia-task-queue';
@inject(DOM.Element, TaskQueue)
@customAttribute('ddl')
export class Select2CustomAttribute {
constructor(element, taskQueue) {
this.element = element;
this.taskQueue = taskQueue;
}
bind(bindingContext) {
this.bindingContext = bindingContext;
}
attached() {
this.taskQueue.queueMicroTask(() => {
this.create();
});
}
create() {
//Object.assign(defaultOpts, this.options);
$(this.element).select2()
.on('change', (evt) => {
if (evt.originalEvent) {
return;
}
this.element.dispatchEvent(new Event('change', { bubbles: true }));
//reset value to avoid multiple-select problems
let value = this.bindingContext[this.element.getAttribute('value.bind')];
this.bindingContext[this.element.getAttribute('value.bind')] = [];
this.bindingContext[this.element.getAttribute('value.bind')] = value;
});
}
}
用法
<require from="./select2-attribute"></require>
<select style="width: 200px;" ddl value.bind="selectedValue" change.delegate="valueChanged()" multiple>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
运行示例:https://gist.run/?id=2189fda060e77e3f735ce59528df79b8
如果您需要动态选项,则必须再次销毁并创建 select2 或类似的东西(如果您愿意,我有一些示例)。