在默认的ember js上选择选择

时间:2013-03-30 08:54:40

标签: ember.js

我有一个模型Currencies。模型中的字段为name:stringdefault:boolean。 在后端,只有一个数据库中的记录可以default:true.我希望默认情况下在Ember js中选择它。

请举例说明如何选择并使用

示例:

name: type1  default: false
name: type2  default: true
name: type3  default: false

我想生成这样的选择:

<selected>
  <option>type1</option
  <option selected=selected>type2</option
  <option>type3</option
</selected>

Route.js

@route 'addincome', { path: 'operations/addincome' }
EmberMoney.AddincomeRoute = Ember.Route.extend
  model: ->
    EmberMoney.IncomeOperation.createRecord()
  setupController: (controller, model) ->
    controller.set('currencies', EmberMoney.Currency.find())
    controller.set('content', model)

addincome.handlebars

//带有收入记录的一些输出

{{view EmberMoney.Select viewName="select"
                    contentBinding="controller.currencies"
                    optionLabelPath="content.name"
                    optionValuePath="content.id"
                    selectionBinding="controller.defaultType"}}

addincome_controller.js

EmberMoney.AddincomeController = Ember.ObjectController.extend({
  setDefaultCurrency: function(){
    if(this.get('currencies.isLoaded')){
      this.set('defaultType', this.get('currencies').findProperty('default'));
    }
  }.observes('currencies.isLoaded')
})

2 个答案:

答案 0 :(得分:0)

使用selectionBinding进行选择,使用ComputedProperty查找相应的项目

更新

EmberMoney.AddincomeController = Ember.ObjectController.extend({
  setDefaultCurrency: function(){
    if(this.get('currencies.isLoaded')){
      this.set('defaultType', this.get('currencies').findProperty('default'));
    }
  }.observes('currencies.isLoaded')
})

对于观察者使用isLoaded而不是@each的优点是每次添加货币时观察者都不会被触发,而是确保在加载整个集合后设置值,再次它

是用于确定使用哪个用例的

有关findProperty

的详细信息

希望这有帮助

截图List of the currencies

答案 1 :(得分:0)

我的回答建立在已发布的那个上。答案是使用selectionBinding和一种聪明的方法来设置它:

{{view Ember.Select
   contentBinding="controller.types"
   optionLabelPath="content.name"
   optionValuePath="content.id"
   selectionBinding="controller.selectedCurrency"
}}

EmberMoney.IncomesController = Ember.ArrayController.extend({
  selectedCurrency : null,
  currenciesObserver: function(){
    var currencies = this.get("currencies");
    var default = currencies.findProperty("default");
    if(default)
      this.set("selectedCurrency", default);
  }.observes('currencies.@each')
});

该解决方案如何运作?

  • 我们在Select控件和控制器之间设置了selectionBinding(双向)。如果在属性“selectedCurrency”中设置控制器中的货币,则它将是Select控件中的选定值。反之亦然,如果您在选择框中选择货币,它将在您的控制器中设置。
  • 我正在使用观察者的助手进行初始设置。 每次观察的货币数组发生变化时都会调用观察者。
  • 每次调用它时,它都会尝试查找默认货币。如果找到一个,则将其设置在selectedCurrency属性中。现在,selectionBinding会为你踢出它的魔力。
  • 此解决方案的另一个优点是,如果用户选择其他货币,您可以轻松地从属性中获取所选值。
相关问题