Thomas Peiffer
Thomas Peiffer

Reputation: 15

get a model from other controller in emberjs in view

I got a problem with a bigger project in ember, I want to get information from a model when i'm in a template that is not associated with the controller for that model.

I got these templates:

<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>

in the routes I fetch the appropriate models so for the community i got 1 community and in the communityUsers i have an array with users

does anyone know the best solution for this?

Upvotes: 0

Views: 105

Answers (2)

intuitivepixel
intuitivepixel

Reputation: 23322

I got a problem with a bigger project in ember, I want to get information from a model when i'm in a template that is not associated with the controller for that model.

Assuming you get your communities like this:

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

Further assuming you want to have access from a controller that is not related to your CommunityController (which get's it's content set after the model hook returns) you could use the needs API and define a dependance to it

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')
});

So now in your communityUsers template you are able to access those properties

<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>

And the best of all this, everything will stay up to date since it's bound.

Hope it helps.

Upvotes: 1

Hyder
Hyder

Reputation: 1463

So from what I've understood, you are trying to access the model of communityController inside the template of it's child template communityUsers. For that you've to define your communityUsersController to need the communityController by

needs: ['community']  

and then in your template

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

Upvotes: 1

Related Questions