从视图中的emberjs中获取其他控制器的模型

时间:2013-08-23 15:03:59

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

我在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个社区,在社区用户我有一个用户数组

有人知道最佳解决方案吗?

2 个答案:

答案 0 :(得分:1)

因此,根据我的理解,您正尝试在其子模板communityController的模板中访问communityUsers模型。 为此,您需要将communityUsersController定义为{/ 1}}

communityController

然后在你的模板中

needs: ['community']  

答案 1 :(得分: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>

最重要的是,一切都将保持最新,因为它受到约束。

希望它有所帮助。

相关问题