Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set bootstrap active tab on refresh in Angular JS

I am creating tabs as:

 <tabset class="content-tabset no-margin">
<tab ng-repeat="t in t.values" heading="{{t.name}}" active="t.active">
  //other stuff
</tab>
</tabset>

Now within this other stuff I also have button which when clicks updates the row and refreshes that part. When the refresh happens it also resets the tab I am currently on. So if I am tab two and click on the button, the panel refreshes and I come back on tab 1. How can I prevent this?

like image 347
user1563677 Avatar asked Apr 28 '15 07:04

user1563677


People also ask

How to set active tab style with AngularJS?

How to set active tab style with AngularJS? To set an active tab style using AngularJS we need to use isActive and the ng-controller method . The ng-controller Directive in AngularJS is used to add controller to the application.

How to make a tab using angular UI bootstrap?

Angular UI Bootstrap is an Angular JS framework created by Angular UI developers for providing better UI which can be used easily. First, add Angular UI bootstrap scripts needed for your project. Make tab with its UIBootStrap classes which will set the UI look for the tab.

How to get last active tab selected on page reload in Bootstrap?

In Bootstrap, if you refresh the page the tab is reset to default setting. However, you can use the HTML5 localStorage object to save some parameter for the current tab locally in the browser and get it back to make the last active tab selected on page reload. Let's try out the following example to understand how it basically works:

Why use ng-bootstrap components?

Bootstrap components are getting used for a long time by developers to add multi-device and screen support. So using ng-bootstrap components not only fasten the development process but also adds up responsive behavior to these components by default.


1 Answers

Use localStorage. Set it on selecting tab. To get boolean value of active state for current tab use ng-init.

<tabset class="content-tabset no-margin">
  <tab 
    ng-repeat="t in t.values" 
    heading="{{t.name}}" 
    ng-init="isActive = isActiveTab(t.name, $index)"
    active="isActive"
    select="setActiveTab(t.name)">
    //other stuff
  </tab>
</tabset>

And in your controller

$scope.setActiveTab = function( activeTab ){
    localStorage.setItem("activeTab", activeTab);
};

$scope.getActiveTab = function(){
    return localStorage.getItem("activeTab");
};

$scope.isActiveTab = function( tabName, index ){
    var activeTab = $scope.getActiveTab();
    return ( activeTab === tabName || ( activeTab === null && $index === 0 ) );
};

NOTE: Since your t has no unique ID for tabs, names should be unique to detect active tab correctly.

See example JSFiddle.

like image 109
Rene Korss Avatar answered Sep 19 '22 16:09

Rene Korss