Responsive Bootstrap and AngularJS routing

Update: If you’re combinding Bootstrap with AngularJS you might want to consider using Angular UI Bootstrap project. Basically this removes the dependency on jQuery. I haven’t tried it yet but it looks promising.

Just noticed a problem with the awesome Responsive Bootstrap template when combined with AngularJS and routing.

The ‘collapse button’ in the navbar that appears with small device widths no longer works when you’re using AngularJS routing. This is because the collapse button is actually an anchor tag and in the default template it has an empty href attribute. In practice this means that if you click it the browser stays on the home page.

But when AngularJS appends ‘#/’ to the home URL this anchor tag directs the browser to the home page. Then AngularJS appends ‘#/’ again and this confuses the browser.

The solution is to edit the boilerplate bootstrap HTML and to edit bootstrap.js.

In the boilerplate HTML find this:

<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
 <span class="icon-bar"></span>
 <span class="icon-bar"></span>
 <span class="icon-bar"></span>

then add href=”#” to the anchor tag.

Then in bootstrap.js find this:

 * ==================== */
$(document).on('', '[data-toggle=collapse]', function (e) {
 var $this = $(this), href
 , target = $this.attr('data-target')
 || e.preventDefault()
 || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
 , option = $(target).data('collapse') ? 'toggle' : $
 $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed')

and add ‘return false;’ before the last line with the closing braces:

This prevents the anchor tag’s default behavior, the navigation.

Hope this helps!