【问题标题】:get a model from other controller in emberjs in view在视图中从 ember js 中的另一个控制器获取模型
【发布时间】:2013-08-23 15:03:59
【问题描述】:

我在 ember 中遇到了一个更大的项目问题, 当我处于与该模型的控制器无关的模板中时,我想从模型中获取信息。

我得到了这些模板:

<script type="text/x-handlebars" data-template-name="community">
   {{model.name}}
   {{outlet}}
</script>

//users is a subroute from community
<script type="text/x-handlebars" data-template-name="communityUsers">
   //assume i want to display something from a community here like:
   {{community.id}}
   {{#each user in model}}
     <li>{{user.name}}</li>
   {{/each}}
</script>

在路线中,我获取了适当的模型,因此对于社区,我得到了 1 个社区,而在 communityUsers 中,我有一个包含用户的数组

有人知道最好的解决方案吗?

【问题讨论】:

  • 我认为您需要以更具体的方式解释问题。你想从模型中得到什么信息?不要要求“最好的解决方案”,而是专门要求解决您的问题的解决方案。

标签: ruby-on-rails model-view-controller model ember.js


【解决方案1】:

我在 ember 中遇到了一个更大的项目的问题,当我在一个与该模型的控制器没有关联的模板中时,我想从一个模型中获取信息。

假设你的社区是这样的:

App.CommunityRoute = Ember.Route.extend({
  model: function() {
    return App.Community.find();
  }
});

进一步假设您希望从与您的 CommunityController 无关的控制器访问(在模型挂钩返回后获得它的内容集),您可以使用 needs API 并定义对它的依赖

App.CommunityUsersController = Ember.Objectontroller.extend({
  // here dependence definition
  needs: ['community'],
  // create an observer that returns the community you want
  // I've chosen just the first one
  choosenCommunity: function() {
    return this.get('controllers.community').objectAt(0);
  }.observes('controllers.community')
});

所以现在您可以在 communityUsers 模板中访问这些属性

<script type="text/x-handlebars" data-template-name="communityUsers">
   //assume i want to display something from a community here like:
   {{choosenCommunity.id}}
   {{#each user in choosenCommunity.users}}
     <li>{{user.name}}</li>
   {{/each}}
</script>

最棒的是,自从绑定后,一切都会保持最新状态。

希望对你有帮助。

【讨论】:

    【解决方案2】:

    所以据我了解,您正试图在其子模板communityUsers 的模板内访问communityController 的模型。 为此,您必须通过

    定义您的 communityUsersController 以需要 communityController
    needs: ['community']  
    

    然后在你的模板中

    {{#each user in controllers.community.model}}
     <li>{{user.name}}</li>
    {{/each}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-16
      • 2013-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      相关资源
      最近更新 更多