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

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...

Unchecked AngularJS checkbox when a different option is selected

<select ng-model="choose"> <option value="1"></option> <option value="2"></option> <option value="3"></option> </select> If the selected value is 1 or 3, a checkbox should appear. <input type ...

Ways to verify if fields within an Embedded Document are either null or contain data in Node.js and Mongodb

I need to verify whether the elements in the Embedded Document are empty or not. For instance: if (files.originalFilename === 'photo1.png') { user.update( { userName: userName ...

Guide to organizing real-time event additions for a scheduler using Angular

Seeking guidance on structuring logic efficiently in Angular for rendering calendars with event objects. The Task at Hand In my current project, I need to display a visual calendar using HTML and dynamically insert event objects from a list of events int ...

Determine whether an element is currently focused using a Vue.js directive

I'm attempting to verify if an element is currently in focus, specifically an input field, and then apply a class to another element. This is the code I have been working on, but for some reason the hasFocus() function isn't functioning as expect ...

using Angular and RxJS to filter out an element from an array

One of the functions in my service is a delete function. This function calls an API that returns either true or false. If the response is true, I then proceed to find the index of the item in my array, splice it out, and return the updated array. Here&apos ...

Sharing state between components in NextJS involves using techniques like Context API, passing

I am trying to pass state between pages in Next.js. In my App.js, I have wrapped it in a context provider like this: import { useRouter } from 'next/router' import { ClickProvider } from '../context/clickContext' function MyApp({ Compo ...

Implementing ExpressJS with MongoDB on a MERN Development Stack

After configuring my ExpressJS & MongoDB client and running Nodemon, I consistently encounter the following warning: "DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the ...

Retrieve the date from 7 days ago and display it in the format "2015-06-23" using JQuery/JavaScript

Looking to retrieve last week's date in the following format: "2015-06-23", as opposed to "2015-06-16". JavaScript: t = new Date(); // Tue Jun 23 2015 21:00:47 GMT-0700 (PDT) t.toISOString(); // "2015-06-24T04:00:47.955Z" The current date format i ...

Using Node.js to showcase MySQL data in an HTML table

Currently, I am in the process of learning how to utilize node.js with mysql. Despite my efforts to search for comprehensive documentation, I have not been successful. I have managed to display my mysql data on my browser, but ultimately I aim to manage it ...

Adjusting element position while scrolling

Objective The goal is to have the page navigation display lower on the page by default. This will provide a cleaner layout as shown in the image below. Context An interactive element for navigation was implemented utilizing Headroom.js. This library d ...

"Enhance your online shopping experience with a React.js popup modal for

In the midst of developing a shopping cart, I find myself facing a challenge in making the modal pop up when clicking on the shopping cart icon. The semantic-ui documentation for modals has not provided clear instructions on achieving this functionality, s ...

Having trouble adjusting the refresh timer based on user focus with setTimeout

For the past few days, I've been utilizing an ajax call to dynamically refresh specific elements of my webapp every 5 seconds. The implementation with setInterval(refreshElements, 5000) worked perfectly fine. However, now I am considering whether the ...

Ways to retrieve arrow information in JavaScript?

I'm currently retrieving tabular data in Arrow format from an API where the response content-type is application/vnd.apache.arrow.stream. Within my React code, I am attempting to parse this response. However, I'm uncertain if this approach is the ...

How can getters in vuex be utilized uniquely?

After dedicating two weeks to studying Vuex, I find myself pondering the true significance and purpose of getters in the framework. I ran the following code snippet and everything seems to be functioning properly. this.$store.getters["app/url"] ...

Running the gulp uncss command with regex to ignore specific elements is not functioning as expected

I have been attempting to integrate uncss into my gulp workflow. In order to exclude certain classes, such as those added through javascript, I am specifying these classes with "ignore" (specifically, I am trying to remove the css from the jquery plugin m ...

Navigating through streets using a map provided by Google along with services

I've never incorporated Google API into my web project before, but now I'm ready to tackle it. Unfortunately, as a beginner, I find it challenging to understand the tutorials available online. Here are my requirements: 1) I have a spring rest se ...

transferring data between react components

I am currently working on breaking down code into smaller components, starting with the snippet below from Rows.jsx. I am struggling to grasp how props are passed between parent and child components. Despite reading several guides and articles, I remain un ...

Troubleshooting Recursive Logic Problem with hasOwnProperty in JavaScript and JSON

JSON data with a specific problem highlighted by the comment // doesn't get parsed currently: var oarsObject = [{ "coordinateReferenceSystem": "26782,15851 <-- not in a value", "positionReferenceType": "geogWgs84", "geogWgs84": ...

The jQuery datetimepicker fails to reflect changes made to the minDate property

I have encountered a datetimepicker object that was previously set up with the following configuration: $('#startDate').datetimepicker({ monthNames: DATE_TIME_MONTHS_NAMES, monthNamesShort: DATE_TIME_MONTHS_NAMES_SHORT, dayNames: DAT ...