NJP
NJP

Reputation: 835

Add class to link when on specific pages

I have two routes that are both nested under the same resource, like so:

Router.map(function() {
  this.resource('dashboard', function() {
    this.route('foo');
    this.route('bar');
  });
});

Currently, in my app/templates/application.hbs, I have the navigation set up like this:

<ul class="nav navbar-nav">
  {{#link-to "dashboard.foo" tagName="li"}}
    <a {{bind-attr href="view.href"}}>Dashboard</a>
  {{/link-to}}
</ul>

That, obviously, links to dashboard.foo. However, that link also needs to be active on dashboard.bar. It has to point to dashboard.foo instead of dashboard.

I've tried creating a computed property in the application controller, like the answer to this question, but the currentPath never showed that it was on the dashboard. This is my attempt at it:

export default Ember.Controller.extend({
  isDashboardRoute: function() {
    var routeName = this.get('currentRouteName');
    var currentPath = this.get('currentPath');
    console.log(routeName); // "loading"
    console.log(currentPath); // "loading"
  }.property('currentPath')
});

I then tried to add a dummy link-to that would show it as active (as described on this Stack Overflow question), but it seems that it instead fires two events at once. This is that attempt:

// application.hbs
{{#link-to "dashboard" tagName="li" href=false eventName="dummy"}}
  {{#link-to "dashboard.foo"}}Dashboard{{/link-to}}
{{/link-to}}

Any ideas?

Edit

After inserting the answer below into my code, here's what I now have:

{{#link-to "dashboard.foo" tagName="li" current-when="dashboard"}}
  <a {{bind-attr href="view.href"}}>Dashboard</a>
{{/link-to}}

I couldn't have the nested link-to because it would mark both the li as well as the a as active, when I only needed the former to be active.

Upvotes: 1

Views: 128

Answers (1)

Aaron Renoir
Aaron Renoir

Reputation: 4381

You can use the current-when property.

{{#link-to "dashboard" tagName="li" href=false eventName="dummy" current-when="dashboard"}}
  {{#link-to "dashboard.foo"}}Dashboard{{/link-to}}
{{/link-to}}

There is also a feature flag for ember-routing-multi-current-when

Upvotes: 2

Related Questions