Accessing a Controller Property from Index Template (2.3.0)


#1

New to ember, tried to avoid controllers but after reading up on things it seems like the most convenient way to handle UI state that needs to be available in a route and component. A service seems like overkill this stuff as it only applies to this specific route/template/component stack.

The pattern works fine for top level routes but I haven’t discovered how to make it work for a child template / nested route.

routes/application.js

export default Ember.Route.extend({    
    setupController: function(controller, model) {
        this._super(controller, model);
        controller.set("uiStateVariable", "hello");
    }
}

templates/application.js

<h1>{{uiStateVariable}}</h1>  // <h1>hello</h1>
{{outlet}}

templates/index.js

<h2>{{uiStateVariable}}</h2>  // <h2></h2>  (not available here)
{{awesome-component uiStateVariable=uiStateVariable}}  (not available here)

Seems like there was an old pattern of {{controllers.application.uiStateVariable}} but now ember cries foul when it sees that.


#2
// index controller
export default Ember.Controller.extend({
  app: Ember.inject.controller('application')
});
{{app.uiStateVariable}}

#3

Thank you @jasonmit! I did the following and it worked.

controllers/index.js

export default Ember.Controller.extend({});

routes/application.js

export default Ember.Route.extend({    
    setupController: function(controller, model) {
        this._super(controller, model);
        this.controllerFor("index").set("uiStateVariable", "hello");
    }
}

templates/index.js

<h2>{{uiStateVariable}}</h2>  // <h2>hello</h2>  (available here!)
{{awesome-component uiStateVariable=uiStateVariable}}  (available here!)

I was a bit surprised the name of the controller had to be just “index” and not “application-index” or “application.index” (the latter two variations didn’t work). If I have another top level route with an index template will that controller also be called just index?

Edit: Found an old explanation of naming conventions that clears up this concept!