home
  • Blog
1.13
  • Getting Started
  • The Object Model
  • Templates
  • Routing
  • Components
  • Controllers
    • Introduction
    • Representing Multiple Models
    • Managing Dependencies Between Controllers
  • Models
  • Testing
  • Ember Inspector
  • Configuring Ember.js
  • Understanding Ember.js
  • Contributing to Ember.js
Old Guides - You are viewing the guides for Ember v1.13.0.
Go to v5.0.0

Managing Dependencies Between Controllers

Edit pencil

Sometimes, especially when nesting resources, we find ourselves needing to have some kind of connection between two controllers. Let's take this router as an example:

app/router.js
var Router = Ember.Router.extend({});

Router.map(function() {
  this.route("post", { path: "/posts/:post_id" }, function() {
    this.route("comments", { path: "/comments" });
  });
});

export default Router;

If we visit a /posts/1/comments URL, our Post model will get loaded into a PostController's model, which means it is not directly accessible in the CommentsController. We might however want to display some information about it in the comments template.

To be able to do this we inject the PostController into the CommentsController (which has the desired Post model).

app/controllers/comments.js
export default Ember.Controller.extend({
  postController: Ember.inject.controller('post')
});

Once comments has access to the PostController, a read-only alias can be used to read the model from that controller. In order to get the Post model, we refer to postController.model:

app/controllers/comments.js
export default Ember.Controller.extend({
  postController: Ember.inject.controller('post'),
  post: Ember.computed.reads('postController.model')
});
app/templates/comments.hbs
<h1>Comments for {{post.title}}</h1>

<ul>
  {{#each model as |comment|}}
    <li>{{comment.text}}</li>
  {{/each}}
</ul>

For more information about dependency injection in Ember.js, see the dependency injection guide. For more information about aliases, see the API docs for aliased properties.

left arrow
Representing Multiple Models
We've finished covering Controllers. Next up: Models - Introduction
right arrow
Team Sponsors Security Legal Branding Community Guidelines
Twitter GitHub Discord Mastodon

If you want help you can contact us by email, open an issue, or get realtime help by joining the Ember Discord.

© Copyright 2023 - Tilde Inc.
Ember.js is free, open source and always will be.


Ember is generously supported by
blue