Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set link 'active' for multiple different routes in EmberJS

I'd like to set the 'active' class on an Ember link-to helper for more than one route, where the routes are not nested. ie. if I have a link to route1 I would like it to be active when the current route is route1 or route2.

Something, like:

{{#link-to 'route1' currentWhen="route1, route2"}}Things-N-Stuff{{/link-to}}

My next ideal scenario is set (or find) a boolean when the route is active and then do something like:

{{#link-to 'route1' class="isRoute1:active isRoute2:active"}}Not-as-good{{/link-to}}

But I'd rather pick it up for free. Perhaps there is a default isRoutename boolean that isn't in the docs yet...?


No answers yet. I ended up doing this:

{{#linkTo "things" tagName="li" href=false}}
    <a {{bindAttr href="view.href"}} {{bindAttr class="isThingsLinkActive:active"}}>Things</a>
{{/linkTo}}

And then in the App.ApplicaitonController

isThingsLinkActive: function(){
    return ['things.index','thing.index','stuff.index'].contains( this.get('currentPath') );
}.property('currentPath'),

It means I need to have something like thins in my app controller for each 'overloaded' link. Wouldn't it be cleaner to capture this entirely in the template using default flags/attributes generated by ember? I'm open to a more elegant solution... anyone?

like image 442
genkilabs Avatar asked Nov 27 '13 18:11

genkilabs


2 Answers

According to the link-to#active documentation, you can do this by using a space delimited "currentWhen", but this requires Ember 1.8.

{{#link-to 'route1' currentWhen="route1 route2"}}Things-N-Stuff{{/link-to}}

This may also be a feature you can enable on earlier builds:

See 'ember-routing-multi-current-when' on https://github.com/emberjs/ember.js/blob/master/FEATURES.md

Alternatively, you can override the link-to helper with one of the methods described in this SO post:

Is there a way to pass an array to currentWhen in EmberJS?

like image 85
Ryan Rapp Avatar answered Oct 20 '22 20:10

Ryan Rapp


Currently as of 3.2 the correct syntax is:

{{#link-to 'fruits.index' current-when="fruits.index apples.index"}}Link text{{/link-to}}

Sorry, tried to edit the original answer but the change is less than 6 characters.

like image 40
Chris Turner Avatar answered Oct 20 '22 19:10

Chris Turner