Make the current tab the active tab with the help of AngularJS

I have a set of five tabs that are functioning correctly. However, when I refresh the page, the active tab reverts back to its default state instead of staying in its current active state. Can anyone help me identify where I may be making a mistake?

Here is the HTML code:

    <div class="container">
    <section ng-app="myApp" ng-controller="TabController as tab">
       <ul class="nav nav-pills">
            <li ng-class="{active:tab.isSet(1)}"><a href ng-click="tab.setTab(1)">Home</a></li>
            <li ng-class="{active:tab.isSet(2)}"><a href ng-click="tab.setTab(2)">Underwriting</a></li>
            <li ng-class="{active:tab.isSet(3)}"><a href ng-click="tab.setTab(3)">Operations</a></li>
        </ul>

        <div ng-show="tab.isSet(1)">
             <h4>Home</h4>
        </div>
        <div ng-show="tab.isSet(2)">
             <h4>Underwriting</h4>
        </div>
        <div ng-show="tab.isSet(3)">
             <h4>Operations</h4>
        </div>
    </section>
</div>

And here is the JavaScript code:

    (function () {
    var app = angular.module('myApp', []);

    app.controller('TabController', function () {
        this.tab = 1; // This is where my logic seems to be failing.

        this.setTab = function (tabId) {
            this.tab = tabId;
        };

        this.isSet = function (tabId) {
            return this.tab === tabId;
        };
    });
})();

For a working demo, you can visit http://jsfiddle.net/fwoxdjsu/

Answer №1

Remember to save the tab index in local storage so it can be retrieved on page refresh. Convert the stored string index to a number before using it.

this.tab = +localStorage.getItem('tabIndex') || 1;
this.setTab = function (tabId) {
  this.tab = tabId;
  localStorage.setItem('tabIndex', tabId);
};

Check out the code on jsFiddle

Answer №2

Revised JavaScript

(function () {
    var app = angular.module('myApp', []);

    app.controller('TabController', function () {
        if(typeof(localStorage.currentTab)=="undefined")
            this.tab = 1;
        else 
            this.tab = parseInt(localStorage.currentTab);

        this.setTab = function (tabId) {
                localStorage.currentTab=tabId;
            this.tab = tabId;
        };
        this.isSet = function (tabId) {
            return this.tab === tabId;
        };
    });
})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display all options by clicking using the Chips and autocomplete features of AngularJS Material

I am utilizing the md-contact-chips component in a AngularJS application with autocomplete feature. As someone who is new to Angular, I am currently exploring ways to display the entire list of options immediately upon clicking the input field, rather than ...

Ensure the left and right screen widgets remain fixed in their positions as the user scrolls down the page using the spacebar

Currently, I have a webpage that showcases products with a large height attribute. I am looking for a way to make the page scroll down when the user hits the space bar to view more products. However, I want my screen widgets such as the shopping cart and ...

Unable to comprehend the error message stating that using the $http call is not permitted in AngularJS

Issue encountered while making a DELETE call using $http: DELETE 'url'/?$$hashKey=021&id=2&idHike=2&label=pelle&onMe=true&weight=110 405 (Method Not Allowed) If anyone has any suggestions... Frontend: $scope.del ...

Utilizing ReactJs to Generate a Random Number for Visualization in a Material UI Progress Bar

I am looking to generate a random number for my test functionality in order to display it within a Material UI Progress bar. I have successfully implemented this piece of JavaScript code on JSFiddle, but now I want to integrate it into my React application ...

``When executing the `npm install` command, it does not install the sub-dependencies of a local package

I am facing an issue with my packages. One package named package-a has a dependency on another package called package-b which is not published on npm but resides in my file system. When I try to run npm install from the directory of package-a, the dependen ...

Encountered a cross-domain error with node.js and jQuery: ERR_CONNECTION_REFUSED

Just beginning my journey with Node.js. I've set up a basic node/express application that serves a single webpage featuring a button. When clicked, this button triggers a jQuery ajax request to an Express route. The route callback then makes an http ...

What is the best way to ensure that a mongoose .exec() callback has completed before checking the response object in express?

I am currently developing an application that utilizes Express, Mongoose, and Jest for testing. In order to test my application, I have set up a mongodb in local memory for testing purposes. However, I am facing an issue in some of my tests where the callb ...

Material-ui does not adjust Typography color based on the theme selected

Exploring material-ui, I have implemented two themes: const darkTheme = createMuiTheme({ palette: { type: "dark" } }); const lightTheme = createMuiTheme({ palette: { type: "light" } }); However, when utilizing the Typography component, t ...

Steps for accessing my operational Angular 2 application on a virtual machine

After developing an Angular 2 app, I encountered a discrepancy in functionality when running it on my local machine versus my Amazon EC2 virtual machine. On my local machine, executing npm start generates a string indicating that the app is being served at ...

Displaying JSON data using AngularJS

Just starting out with AngularJS and I'm facing an issue. I have a JSON object coming from my Spring controller, but I'm not sure how to use or print it in my JSP. I attempted the following code snippet. The console displays the JSON perfectly f ...

Converting hexadecimal to binary using Javascript or Typescript before writing a file on an Android or iOS device

Hey everyone! I'm facing a puzzling issue and I can't seem to figure out why it's happening. I need to download a file that is stored in hex format, so I have to first read it as hex, convert it to binary, and then write it onto an Android/ ...

Accessing loop variables in Render and passing them into componentDidMount() in ReactJS to include as a query parameter in an API call

Within the render function, I am using a loop to rotate an array of coordinates in order to position markers on a map. {coords.map(({ lat, lng }, index) => (code goes here and so on))} I intend to replace query parameters with the variable generated f ...

The pictures are not showing up in the photo album

I am currently in the process of building a swim image gallery inspired by the Flex Panel Gallery project from Javascript30 (Repo Link). Upon previewing the site in a browser, I encountered an issue where the images extend beyond the frame, leaving only t ...

Is there a method to display the Freshservice app on portal pages specifically for Requesters' view?

Here is what I need: 1. The user will input a subject. 2. Based on the subject, I need to make a call to a third-party REST API (Unfortunately, it is currently blocked by CORS and even JSONP requests are not working). 3. After receiving the response, I w ...

Obtaining a pdf file using javascript ajax is a straightforward process

Looking to access my JavaScript file generated by a microservice (byte[]): public int retrieveLabel(Request request, Response response) throws IOException { response.header("Access-Control-Allow-Origin", "*"); ArrayList<JSONObject> orders = ...

Issue encountered in the express route when attempting to send an email to the user with nodemailer and reactjs

When attempting to send an email to the user who submitted the application using ReactJS and Nodemailer, an error stating "route not found" is encountered. Warning: Location "/contact?name=milan&email=xedikaka%40gmail.com&phone=9843698469&city ...

Sharing Data Between Controllers in AngularJS

I am faced with a challenge involving two Angular controllers: function Ctrl1($scope) { $scope.prop1 = "First"; } function Ctrl2($scope) { $scope.prop2 = "Second"; $scope.both = Ctrl1.prop1 + $scope.prop2; //Ideally, I would like to achieve t ...

Performing multiplication and calculating the final sum of an array object in Node JS

I am looking to calculate the total based on an array of objects sum of each row = sum of costs * quantity total = sum of (sum of each row) Below is the object array that I am working with const newArray = [ { 'LOA Qty': '2000', ' ...

What could be causing the issue of $.ajax being undefined while utilizing jQuery in Node.js?

I'm currently testing a module on Node.js that is meant for client-side use. In order to make $.ajax work, I need some guidance. To begin with, I have installed jQuery on the project using: $ npm install jQuery Despite this, when I try to access $. ...

Creating dynamic forms using AngularJS with a click event for the action button

I am looking to dynamically generate form fields based on the JSON structure. Currently, I have successfully rendered the fields on the webpage using a JavaScript file. However, I need assistance in adding action items to the "button" part. For example, I ...