问题
I'm using Twitter Bootstrap and have a navbar with a regular link and a dropdown link. Using ember's link-to helper, the regular link automatically gets the "active" class when clicked, as do the menu items in the dropdown menu. However, I cannot for the life of me figure out what the best way to get the parent li tag to get the "active" class when one of the dropdown menu items is selected. I've tried creating a component out of the dropdown menu but I cannot get it to work.
Markup in .emblem:
.navbar.navbar-default.navbar-static-top
ul.nav.navbar-nav
//---------//
// Account //
//---------//
link-to 'admin.business.index' tagName="li" href=false
a href="#" Account
//----------//
// Branding //
//----------//
li.dropdown
a.dropdown-toggle data-toggle="dropdown" href="#"
' Branding
span.caret
ul.dropdown-menu role="menu"
link-to 'admin.business.design' tagName='li' href=false
a href="#" Design
link-to 'admin.business.email' tagName='li' href=false
a href="#" Email Templates
link-to 'admin.business.url' tagName='li' href=false
a href="#" Vanity URL
I thought maybe I could nest the link-tos by replacing the "Branding" wrapper
li.dropdown
with
link-to 'admin.business.design' tagName='li' href=false class="dropdown"
but that makes the entire dropdown element a link to "admin.business.design".
I've created a bin here: http://emberjs.jsbin.com/cosute/2/edit?html,output.
You can see that "Account" and "Thing" are active when the route is, and the submenu items under "Branding" are as well, but I need "Branding" to be selected when a dropdown item under it is as well.
回答1:
JSBin
This is the solution I used. Instead of making {{link-to}} be a li, make a component that is a li. This component makes use of the work Ember does in setting the active class for any link-to to the current route:
App.NavItemComponent = Ember.Component.extend({
tagName: 'li',
classNameBindings: ['active'],
active: function(){
return this.get('childViews').isAny('active');
}.property('childViews.@each.active')
});
This works because we are observing all of the link-to active properties which are set by ember with the parameter passed into the property(). The active property is recomputed for all link-to helpers each time a route changes.
来源:https://stackoverflow.com/questions/26242986/add-active-class-to-bootstrap-dropdown-menu-when-dropdown-link-selected-with