2013-12-11 42 views
0

我有嵌套模型的结构是这样的:嵌套模型数据控制器支持

App.Survey = DS.Model.extend({ 
     name: DS.attr('string'), 
     questions: DS.hasMany('question', {async: true}) 
    }); 

    App.Question = DS.Model.extend({ 
     questionName: DS.attr('string'), 
     parentQuestionId: DS.attr('number'), 
     position: DS.attr('number'), 
     questionLayoutId: DS.attr('number'), 
     questionLayoutName: DS.attr('string'), 
     childQuestions: DS.hasMany('question', {async: true}) 
    }); 

我有itemController成立有助于使控制器像添加额外的“属性”的模型内容:

App.QuestionsController = Ember.ArrayController.extend({ 
     itemController: 'question' 
    }); 

    App.QuestionController = Ember.ObjectController.extend({ 
     needs: 'questions', 
     questions: Ember.computed.alias("controllers.questions"), 
     editMode: false, 
     hasChildren: function() { 
      return (this.get('childQuestions.length') > 0); 
     }.property('childQuestions'), 

     isBlockQuestion: function() { 
      return this.get('questionLayoutName') == "layout-block" 
     }.property('questionLayoutName') 
    }); 

所以当我参加调查时,我可以看到调查中的问题列表。我的路线是设置这样的:

App.SurveyRoute = Ember.Route.extend({ 
     model: function (params) { 
      return this.get('store').find('survey', params.survey_id); 
     }, 

     setupController: function(controller, model){ 
      this._super(controller, model); 
      this.controllerFor('questions').set('model', model.get('questions')); 
     } 
    }); 

现在有了这个设置,我有项目控制器只有root级别问题的权力,但不是孩子的水平问题。我想知道是否有方法将模型数据绑定到适当的控制器上。

这里是一个JSbin证明我的问题:http://jsbin.com/UROCObi/2/

这可能是有点过分进入,但这个概念是非常简单的。一项调查可以有多个问题,一个问题本身可以有孩子的问题(在我的情况下称为块问题)。正如你所看到的,我无法看到第三级的问题,因为它没有封装在任何控制器中。我是否需要在SurveyRoute中为所有嵌套级别的childQuestion实例化ArrayController,还是有其他更干净的方法来执行操作?

感谢, 迪

回答

1

您可以使用:

{{#each questions itemController="question"}} 
      ... 
      {{#each childQuestions itemController="childQuestion"}} 
        ... 
      {{/each}} 

    {{/each}} 

而且每each里面的上下文是QuestionController和ChildQuestioncontroller的实例,respectevely(我不知道有关的命名惯例)。 不需要使用ArrayController,除非您还需要控制整个数组。

+0

感谢它在jsbin中工作,但我真正的应用程序我不知道为什么我得到“TypeError:this.parentController.childControllers是未定义的”错误!也许它只是需要彻底检查。再次感谢。 –

+0

我认为它与命名约定有关,以及Ember如何使用字符串'childQuestion'来查找Controller类并实例化它 – edpaez

+0

ok我发现我看到的问题是由ember-validation库造成的! –