Search code examples
javascriptangularjstwitter-bootstrapui.bootstrap

UI Bootstrap tabs save active tabs after reload


I need to show active tab after page reload. I found that I need to store active tab name to session or local storage. But for me this not working. Here is html

<uib-tabset>
     <uib-tab active="active" ng-init="isActive = isActiveTab('Info', $index)" index="0" data-toggle="tab" href="#sectionInfo" 
     heading="Info" classes="tabovi" select="setActiveTab('Info')"></uib-tab>
     <uib-tab active="active" ng-init="isActive = isActiveTab('Info 2',$index)" index="1" data-toggle="tab" href="#sectionInfoTwo" 
     heading="Info 2" classes="tabovi" select="setActiveTab('Info')"></uib-tab>
</uib-tabset>

And here is controller

// Save active tab to localStorage
$scope.setActiveTab = function (activeTab) {
    sessionStorage.setItem("activeTab", activeTab);
};

// Get active tab from localStorage
$scope.getActiveTab = function () {
    return sessionStorage.getItem("activeTab");
};

// Check if current tab is active
$scope.isActiveTab = function (tabName, index) {
    var activeTab = $scope.getActiveTab();
    return (activeTab === tabName || (activeTab === null && index === 0));
};

Thank you


Solution

  • You need to store index rather than its name. Refer following code snippet:

    HTML:

    <uib-tabset active="active">
        <uib-tab index="0" data-toggle="tab" heading="Info" select="setActiveTab(0)" classes="tabovi"></uib-tab>
        <uib-tab index="1" data-toggle="tab" heading="Software config" select="setActiveTab(1)"></uib-tab>
        <uib-tab index="2" data-toggle="tab" heading="Hardware config" select="setActiveTab(2)"></uib-tab>
        <uib-tab index="3" data-toggle="tab" heading="Config" select="setActiveTab(3)"></uib-tab>
    </uib-tabset>
    

    Javascript:

    $scope.setActiveTab = function (activeTabIndex) {
        sessionStorage.setItem("activeTab", activeTabIndex);
    };
    
    $scope.getActiveTab = function () {
        return sessionStorage.getItem("activeTab");
    };
    
    // This will set last tab active automatically when page loaded
    $scope.active = parseInt($scope.getActiveTab());