0

我正在尝试学习如何创建一个从多个模型中提取的表单。

例如,Person用户可以指定他们的姓名、城市、Company他们所属Group的(单独的模型)、他们所在的Car(单独的模型)、他们驾驶的(单独的模型)等的表单。我找不到关于如何实现这一点的任何文档。

在我见过的所有示例中,路由负责告诉模板使用哪种单一模型类型。我不知道如何创建从不同模型存储库中提取的下拉列表或预输入。

我怎样才能做到这一点?

4

1 回答 1

1

有几种方法可以做到这一点。

(1) 向您的控制器添加一个属性,该属性为您的下拉菜单返回必要的记录。

http://emberjs.jsbin.com/AqimiFI/4/edit

 setupController: function(controller, model) {
   this._super(controller, model);

   // set an empty array
   controller.set('states', []);

   this.get('store').find('state').then(function(states){
     //once the states are resolved set the states to the records
     controller.set('states', states);
   });
  }

(2) 在您的应用程序中的某个点(无论它看起来是否合适),在您的一条路线中为相关项目创建一个控制器,并将该控制器的模型设置为项目,然后使用需要。我更喜欢这种方法,因为您可以在整个应用程序中使用该控制器,为它添加逻辑并共享它等等......

http://emberjs.jsbin.com/AqimiFI/5/edit

setupController: function(controller, model) {
  this._super(controller, model);

  var states = this.controllerFor('states');
  states.set('model', this.get('store').find('state'));
}

App.ApplicationController = Ember.ArrayController.extend({
  needs:['states'],

  states:function(){
    return this.get('controllers.states');
  }.property('controllers.states')
});

在此示例中,我在应用程序路由中创建了一个状态控制器。这根本没有将它绑定到应用程序控制器/路由,它只是早期的一个钩子,我可以利用它来创建控制器来保存数据。

为了从另一个控制器访问一个控制器,您必须指定您需要它(needs:['states'])。

states 属性返回 states 控制器(重要的是要记住,数组控制器和一般的控制器在 ember 中只是其模型上的装饰器)。Ember 会将所有 get/set 调用代理到模型(如果它们在控制器上不存在)。因此,当我真正返回状态控制器时,您可以将其视为只是返回模型,即状态数组。

因此,您可以尝试在控制器上设置属性,但它可能无法按预期工作。我正在利用这样一个事实,即我知道如果我在模型上设置了一个承诺,它实际上会解决该承诺并用该承诺的结果替换模型。它只是更接近于手动创建控制器的预期行为。

于 2013-10-26T16:30:35.933 回答