是的。在您的控制器中,您必須創建一個屬性以在使用Ember.Select
時保持所選的一個或多個值。
在下面的代碼我設置問候語爲選擇框的內容,在列出的問候(檢查ApplicationRoute
)控制器,我也有一個屬性叫做selectedItems
這我結合Select
和如果視圖加載時沒有選擇任何項目,我使用其他一些屬性來過濾要預先選擇的值(1和3)。
這將渲染一個多選框,其ID爲1或3的項標記爲選定項。你可以在這裏看到的來源:http://jsfiddle.net/schawaska/Y8P4m/
把手:
<script type="text/x-handlebars">
<h1>Test</h1>
{{view Ember.Select
multiple="true"
selectionBinding="controller.selectedItems"
contentBinding="controller"
optionLabelPath="content.text"
optionValuePath="content.id"}}
</script>
的JavaScript:
window.App = Ember.Application.create();
App.Store = DS.Store.extend({
revision: 11,
adapter: 'DS.FixtureAdapter'
});
App.Greeting = DS.Model.extend({
text: DS.attr('string'),
when: DS.attr('date'),
selected: false,
isSelected: function() {
return this.get('selected');
}.property('selected')
});
App.ApplicationController = Em.ArrayController.extend({
preselected: function() {
return this.get('content').filter(function(greeting) {
return greeting.get('id') == 1 ||
greeting.get('id') == 3;
});
}.property('[email protected]'),
selectedItems: function() {
if(this.get('selected.length') <= 0) {
return this.get('preselected');
} else {
return this.get('selected');
}
}.property('selected', 'preselected'),
selected: function() {
return this.get('content').filter(function(greeting) {
return greeting.get('isSelected');
})
}.property('[email protected]')
});
App.Greeting.FIXTURES = [
{id: 1, text: 'First', when: '3/4/2013 2:44:52 PM'},
{id: 2, text: 'Second', when: '3/4/2013 2:44:52 PM'},
{id: 3, text: 'Third', when: '3/4/2013 2:44:52 PM'},
{id: 4, text: 'Fourth', when: '3/4/2013 3:44:52 PM'}
];
App.ApplicationRoute = Em.Route.extend({
setupController: function(controller) {
controller.set('model', App.Greeting.find());
}
});
太棒了!非常感謝你!!!所以,多重選擇的作品。但是現在我意識到我對簡單(不是多個)元素有同樣的問題。我想以編程方式更改所選元素,但它始終顯示第一個元素,而不管給定的值如何。你能舉個例子嗎?再次感謝。我將列出我的代碼,當整個案件正在工作。 – user1984778 2013-03-06 15:59:05
我已經更新了小提琴,用'selectionBinding'添加了一個選擇。請注意,對於這兩個示例,都可能有些事情需要處理。這是一個概念性的例子,顯示你在哪裏添加代碼來做這樣的事情。 – MilkyWayJoe 2013-03-06 16:44:53