使用Ember.Select设置选择默认值

时间:2012-01-25 14:34:48

标签: javascript ember.js

我正在尝试使用Ember.select创建一个下拉列表,我的问题是当它第一次渲染时,我想设置一个默认值。一旦我更改了选择,在刷新页面之前不会检查默认值。

以下是代码:

        ET.selectedAppYearController = Ember.Object.create({
            appYear: null,
            isChanged: function () {
                if (this.appYear != null) {
                    LoadETByAppYearETTypeID(this.appYear.text, ET.selectedEmailTypesController.emailType.email_template_type_id);
                }
            } .observes('appYear'),
            setDefault: function() {
                if (this.appYear.text == 2012) {
                    this.set('selection',2012);
                }
            } .observes('appYear')

        });

观点:

    {{view Ember.Select 
        contentBinding = "ET.appYearController.content" 
        selectionBinding="ET.selectedAppYearController.isDefault"
        optionLabelPath="content.text"
        optionValuePath="content.value"
    }}

我想我需要在selectionBinding上设置一些东西...但是我应该绑定什么样的值? 1.下拉列表值是JSON类型。

4 个答案:

答案 0 :(得分:4)

我打算为此制作一个jsfiddle,但此刻似乎有所下降。如果它稍后恢复,它会编辑一个,因为它们通常会使事情变得更清楚。

如果将视图设置为

{{view Ember.Select 
  contentBinding = "ET.appYearController" 
  selectionBinding="ET.selectedAppYearController.appYear"
  optionLabelPath="content.text"
  optionValuePath="content.value"
}}

然后设置selectedAppYearController,例如:

ET.selectedAppYearController = Ember.Object.create({
  appYear: ET.appYearController.get('lastObject')
}

然后你应该将appYearController中的最后一个元素设置为默认值,当你更改选择时,ET.selectedAppYearController.appYear将反映这一点。

显然,如果您想要除appYearController的最后一个元素以外的其他内容,那么您可以将appYear的值设置为您想要的任何内容。

答案 1 :(得分:2)

我迟到了这个派对,但是在最新版本的ember 0.9.7.1中,你可以在你的Ember.Select中设置一个“提示”属性。它看起来像,

{{view Ember.Select
    prompt="This is selected by default"}}

希望有所帮助。

答案 2 :(得分:1)

从您的代码示例中很难说清楚。您可以做的一件事是提取所有特定于域的要求,并设置一个实时的jsfiddle示例,尝试以更通用的方式完成您尝试执行的操作。 http://jsfiddle.net/您可以在此处查看在其他emberjs帖子中使用jsfiddle的示例。

但我注意到的一件事是你的selectionBinding似乎是错误的。这应该绑定到您尝试设置的值,而不是默认值。如果您愿意,可以在控制器中设置默认值(只需将其分配给selectionBinding绑定的值)。所以如果我理解你的例子,我认为你的selectionBinding应该是“ET.selectedAppYearController.appYear”。

答案 3 :(得分:0)

不确定是否还有人需要,但我这样做的方式是使用类似

的方式绑定值
{{view Ember.Select content=templates optionValuePath="content.id" optionLabelPath="content.name" value=selectedTemplateId class="form-control"}}

然后在控制器中将selectedTemplateId实现为计算属性,同时用作setter和getter:

    selectedTemplateId: ( (key, value)->
    # setter code: 
    if arguments.length > 1
        @set('selTemplateId', value)
        return value

    # getter code
    else
        if @get('selTemplateId')?
            return @get('selTemplateId')
        else
            return @get('templates')?.objectAt(0).id
).property()

抱歉CoffeeScript而不是js。 JS版本位于:http://goo.gl/5FZHFh

计算属性的一些文档:http://emberjs.com/api/classes/Ember.ComputedProperty.html