我有一个简单的Ember应用程序,我有一个输入框,两个选择框和一个按钮。我可以在方法“doSearch”中访问输入框的值,但不能访问选择框的值。 到目前为止,我没有尝试过任何工作 - 我评论了我未能尝试访问选择。我开始认为这必须与我对Ember的有限知识有关。
任何帮助将不胜感激。 这是我的HTML和脚本:
<script type="text/x-handlebars" data-template-name="application">
<div id="headerDiv">
<ul>
<li>
<image src="logo.png" style="width:439px;height:102px;"/>
</li>
<li>
{{input type="text" placeholder="Search content" value=newSearch action="doSearch"}}
</li>
<li>
<button type="button" {{action "doSearch"}}>Search</button>
</li>
<li>{{#link-to 'home'}}Home{{/link-to}} | {{#link-to 'help'}}Help{{/link-to}}</li>
</ul>
</div>
<span class="filter">Content Type:
{{view Ember.Select
content=selectContentType
optionValuePath="content.value"
optionLabelPath="content.label"}}
</span>
<span class="filter">Date:
{{view Ember.Select
content=selectDate
optionValuePath="content.value"
optionLabelPath="content.label"}}
</span>
</script>
这是我试图访问选择框的JavaScript:
App = Ember.Application.create();
App.Router.map(function(){
this.resource('home', { path: '/' });
this.resource('help');
});
App.ApplicationController = Ember.ArrayController.extend({
selectContentType: [
{label: "All", value: "all"},
{label: "Text", value: "text"},
{label: "Image", value: "image"}
],
selectDate: [
{label: "None", value: "none"},
{label: "Today", value: "today"},
{label: "Last 7 days", value: "7days"}
],
actions: {
doSearch: function () {
var searchVal = this.get('newSearch');
if (!searchVal.trim()) {return;}
console.log('got searchVal: ',searchVal );
var selectType = $("#selectContentType").val();
//$("#selectContentType option:selected").val();
//this.get('selectContentType.value');
console.log('got selectType: ',selectType );
}
}
});
答案 0 :(得分:7)
使用两个新变量扩展ApplicationController
以保留所选值:
App.ApplicationController = Ember.ArrayController.extend({
selectedContentType: null,
selectedDate: null,
...
});
并使用Ember.Select
类的selectionBinding
属性绑定到这些变量
<span class="filter">Content Type:
{{view Ember.Select
content=selectContentType
optionValuePath="content.value"
optionLabelPath="content.label"
selectionBinding=selectedContentType}}
</span>
<span class="filter">Date:
{{view Ember.Select
content=selectDate
optionValuePath="content.value"
optionLabelPath="content.label"
selectionBinding=selectedDate}}
</span>
然后您可以通过以下方式轻松访问它们:
App.ApplicationController = Ember.ArrayController.extend({
selectedContentType: null,
selectedDate: null,
...
actions: {
doSearch: function () {
var selectedDate = this.get('selectedDate.value');
console.log( selectedDate );
var selectedType = this.get('selectedContentType.value');
console.log( selectedType );
}
}
});
希望它有所帮助。