Question

I've got an unordered list using Bootstrap and Ember.js. Each list item is a link to display a new post, and whenever you click on the link, Ember adds the class active by default. I'm using Bootstrap nav-pills that turn blue when the class is active. However, Ember makes the link active whereas I'd like it to make the whole <li> active.

Here's my template:

<ul class="nav nav-pills nav-stacked">
    {{#each post in controller}}
        <li class="list-group-item">
            {{#link-to 'post' post}}
                {{post.title}}
            {{/link-to}}
        </li>
    {{/each}}
</ul>

When you click on a link, the <li> looks like this:

<li class="list-group-item">
    <a id="ember360" class="ember-view active" href="#/posts/1">
        A great post
    </a>
</li>

I know that it would be fairly trivial to add this functionality with jQuery, but is there a way to make the <li> active rather than the <a> with Ember or Handlebars directly? I tried putting the {{link-to}} around the <li> and that didn't do the trick.

Was it helpful?

Solution

You can change the link-to generated tag to <li> using tagName="li" option. And keep the <a> tag to just keep the bootstrap style:

<ul class="nav nav-pills nav-stacked">
    {{#each post in controller}}        
          {{#link-to 'post' post tagName="li" class="list-group-item" }}
              <a href="#">{{post.title}}</a>
          {{/link-to}}   
    {{/each}}
  </ul>

See this in action http://jsfiddle.net/marciojunior/YLN5X/

OTHER TIPS

I don't think there is any super easy way, I think the best way would be to extend the LinkView, and register a new helper, link-to-bootstrap, or something along those lines that added the class to the li element instead of the anchor element.

There is a really good project that already does this https://github.com/ember-addons/bootstrap-for-ember

There isn't a built-in way. The active class binding code is internal to link-to, and involves several not-easy-to-abstract pieces.

The best solution is to have the routes set the selected post in the postsController. This would look like:

    setupController: function(controller, model) {
      controller.set('model', model);
      this.controllerFor('posts').set('selection', model);
    },

Then you want to open the item controller for posts (PostController unless you set itemController to something different on PostsController) and do something like this:

    selection: Ember.computed.alias("parentController.selection"),
    isActive: Ember.computed.equal("model", "parentController.selection")

Then in your li:

    <li {{bind-attr class="isActive:active :list-group-item"}}>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top