Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS + Bootstrap remember active tab

I've developed a simple AngularJS app that utilizes the Bootstrap directive. Several of my pages uses tabs. The problem is, when im in a tab (other than the first one) and presses a link that leads to another view and go back (back button in browser or application) from that view, the previously active tab isn't the active anymore.

I guess that Angular somehow uses pushState or something like that to keep track of the previous pages, since the length property of window.history is increased when im navigating within the app. Could i somehow attach extra data to the state which contains information about the active tab?

I've tried using pushState to append a tab parameter to the URL. First time pushState is called it works fine. However, the second time Angular goes into some kind of loop causing the page to crash (eventually). How should i implement this?

like image 459
Anton Gildebrand Avatar asked Nov 01 '22 12:11

Anton Gildebrand


1 Answers

After looking at a combination of several solutions (assist from here: http://bit.ly/1qIemCh) and condensing it down to a working solution, this was the one that allowed AngularJS + Bootstrap Tabs for me. The trick is to leverage the HTML5 pushstate to grab the URL hash from history in JS, find the applicable tab, and show it.

Tabs:

<ul class="nav nav-tabs" role="tablist" id="myTab">
    <li class="active"><a href="#" data-target="#">Home</a></li>
    <li><a href="#/tab2" data-target="#">Tab 2</a></li>
    <li><a href="#/tab3" data-target="#">Tab 3</a></li>
</ul>

This JS will activate the proper tab from history or if being navigated too via a bookmark :

function setActiveTab() {
    var hash = window.location.hash;

    var activeTab = $('.nav-tabs a[href="' + hash + '"]');
    if (activeTab.length) {
        activeTab.tab('show');
    } else {
        $('.nav-tabs a:first').tab('show');
    }
};

//If a bookmark was used to a particular page, make sure to 
//activate the correct tab after initial load:
$(document).ready(function() {
    setActiveTab();
});

//When history.pushState() activates the popstate event, switch to the currently
//selected tab aligning with the page being navigated to from history.
$(window).on('popstate', function () {
    setActiveTab();
});
like image 193
atconway Avatar answered Nov 07 '22 21:11

atconway