Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access current route name from a controller or component

Tags:

ember.js

I needs to apply an "active" class to a bootstrap tab depending on the current route name. The route object contains "routeName" but how to I access this from a controller or component?

like image 218
jax Avatar asked May 12 '15 23:05

jax


4 Answers

Use this this.controllerFor('application').get('currentRouteName');

like image 82
blessanm86 Avatar answered Dec 22 '22 05:12

blessanm86


In fact, you don't need to apply active class by yourself. A link-to helper will do it for you.

See here:

{{link-to}} will apply a CSS class name of 'active' when the application's current route matches the supplied routeName. For example, if the application's current route is 'photoGallery.recent' the following use of {{link-to}}:

{{#link-to 'photoGallery.recent'}}
  Great Hamster Photos
{{/link-to}}

will result in

<a href="/hamster-photos/this-week" class="active">
  Great Hamster Photos
</a>
like image 31
Jeffrey C Avatar answered Dec 22 '22 06:12

Jeffrey C


In the absolutely desperate case, you can look up the router, or the application controller (which exposes a 'currentRouteName' property) via this.container.lookup("router:main") or this.container.lookup("controller:application") from within the component.

If it was a common trend for me, I would make a CurrentRouteService and inject it into my component(s) so that I can mock things more easily in my tests.

There may also be a better answer to come along - but the container.lookup() should knock down your current blocker.

like image 21
Nick Williams Avatar answered Dec 22 '22 04:12

Nick Williams


Since Ember 2.15 you can do this through the public Router service.

router: service(),
myRouteName: computed('router.currentRouteName', function () {
    return this.get('router.currentRouteName') + 'some modification';
}

https://www.emberjs.com/api/ember/release/classes/RouterService

Which worked really well for me since I wanted something computed off of the current route. The service exposes currentRouteName, currentURL, location, and rootURL.

currentURL has the query params, but you would need to parse them from the URL.

like image 34
shadowck5000 Avatar answered Dec 22 '22 06:12

shadowck5000