Emberjs - how to access method of one controller from another controller'

In emberjs pre2 we could access controller or any method in controller from another controller in following way:

App.get('router').get('navController').method1();

Can anybody suggest what could be the similar code for emberjs rc1?

Thanks

Upvotes: 4

Views: 4214

Answers (3)

Def_Os
Def_Os

Reputation: 5467

In Ember 2, this works by injecting the controller you want access to:

export default Ember.Controller.extend({
  nav: Ember.inject.controller(),
});

Or, if you want to specify a name different than the controller name:

export default Ember.Controller.extend({
  navController: Ember.inject.controller('nav'),
});

You can then access the injected controller's methods like this:

this.get('navController').method1()

Upvotes: 2

Mudassir Ali
Mudassir Ali

Reputation: 8041

Inside a Controller or a Route you can try

this.controllerFor("nav").method1()

Attention

This was correct answer when the question was asked but since controllerFor is deprecated, please check the answer by joscas

Upvotes: 3

joscas
joscas

Reputation: 7674

Since controllerFor is deprecated, I think the a more correct way would be with needs:

this.get('controllers.nav').method1()

It requires declaring your needs in your controller:

App.YourController = Ember.ObjectController.extend({
  needs: ['nav'],
  ....

Upvotes: 16

Related Questions