Highlighting the selected tab with an active class

Currently in the process of learning angularJs, I am still new to it and attempting to dynamically add an active class to the recently clicked tab. Within my interface, there are four tabs:

insert, view, update & delete
. My goal is to apply the active class to the 'insert' tab when it's clicked, then switch it to the 'view' tab upon clicking that, and so forth. Despite my attempts, I have been unsuccessful in achieving this functionality. My current code automatically adds the active class to all tabs simultaneously, instead of individually as desired. Any advice or suggestions on how to rectify this issue would be greatly appreciated. Thank you for your patience with my linguistic shortcomings!

body{
    background-color: #e8e8e8;
    margin: 0;
    padding: 0;
}

.menu-content{
    padding: 30px;
    width: 100%;
    margin: 0 auto;
    text-align: center;
}

.menu-content button{
    background-color: dimgrey;
    color: #FFF;
    font-family: "Helvetica Neue", Arial, "Lucida Grande", sans-serif;
    font-size: 16px;
    border: 1px solid dimgrey;
    height: 35px;
    width: 100px;
}

.menu-content button:hover{
    color: gold;
    cursor: pointer;
}

.crud{
    padding: 30px;
    width: 90%;
    margin: 0 auto;
    text-align: center;
    background-color: #fff;
    border: 1px solid #aaa;
}

.active{
    color: gold !important;
    cursor: pointer !important;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="myApp" ng-controller="myController">
    <div class="menu-content">
        <button ng-click="activeClass('insert')" ng-class="{active: true}">Insert</button>
        <button ng-click="activeClass('view')" ng-class="{active: true}">View</button>
        <button ng-click="activeClass('update')" ng-class="{active: true}">Update</button>
        <button ng-click="activeClass('delete')" ng-class="{active: true}">Delete</button>
    </div>
    <div class="crud" ng-show="menu.insert">Insert</div>
    <div class="crud" ng-show="menu.view">View</div>
    <div class="crud" ng-show="menu.update">Update</div>
    <div class="crud" ng-show="menu.delete">Delete</div>
</div>

<script>
    (function(){
        var app = angular.module('myApp',[ ]);
        app.controller('myController', function($scope){
            $scope.menu = {};
            $scope.menu.insert = true;
            $scope.menu.view = false;
            $scope.menu.update = false;
            $scope.menu.delete = false;

            $scope.activeClass = function(tab){
                $scope.menu.insert = false;
                $scope.menu.view = false;
                $scope.menu.update = false;
                $scope.menu.delete = false;
                if(tab == 'insert') $scope.menu.insert = true;
                else if(tab == 'view') $scope.menu.view = true;
                else if(tab == 'update') $scope.menu.update = true;
                else $scope.menu.delete = true;
            }
        });
    })();
</script>

Answer №1

Ensure you use

ng-class="{ active: menu.insert }"
, etc... following is your updated code:

body{
    background-color: #e8e8e8;
    margin: 0;
    padding: 0;
}

.menu-content{
    padding: 30px;
    width: 100%;
    margin: 0 auto;
    text-align: center;
}

.menu-content button{
    background-color: dimgrey;
    color: #FFF;
    font-family: "Helvetica Neue", Arial, "Lucida Grande", sans-serif;
    font-size: 16px;
    border: 1px solid dimgrey;
    height: 35px;
    width: 100px;
}

.menu-content button:hover{
    color: gold;
    cursor: pointer;
}

.crud{
    padding: 30px;
    width: 90%;
    margin: 0 auto;
    text-align: center;
    background-color: #fff;
    border: 1px solid #aaa;
}

.active{
    color: gold !important;
    cursor: pointer !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="myApp" ng-controller="myController">
    <div class="menu-content">
        <button ng-click="activeClass('insert')" ng-class="{active: menu.insert}">Insert</button>
        <button ng-click="activeClass('view')" ng-class="{active: menu.view}">View</button>
        <button ng-click="activeClass('update')" ng-class="{active: menu.update}">Update</button>
        <button ng-click="activeClass('delete')" ng-class="{active: menu.delete}">Delete</button>
    </div>
    <div class="crud" ng-show="menu.insert">Insert</div>
    <div class="crud" ng-show="menu.view">View</div>
    <div class="crud" ng-show="menu.update">Update</div>
    <div class="crud" ng-show="menu.delete">Delete</div>
</div>

<script>
    (function(){
        var app = angular.module('myApp',[ ]);
        app.controller('myController', function($scope){
            $scope.menu = {};
            $scope.menu.insert = true;
            $scope.menu.view = false;
            $scope.menu.update = false;
            $scope.menu.delete = false;

            $scope.activeClass = function(tab){
                $scope.menu.insert = false;
                $scope.menu.view = false;
                $scope.menu.update = false;
                $scope.menu.delete = false;
                if(tab == 'insert') $scope.menu.insert = true;
                else if(tab == 'view') $scope.menu.view = true;
                else if(tab == 'update') $scope.menu.update = true;
                else $scope.menu.delete = true;
            }
        });
    })();
</script>

Answer №2

Gratitude to everyone, I have successfully resolved my issue. The error was in my binding expression for ng-class. I corrected it to ng-class="{active: menu.insert}". Now, I have a clear understanding of how to properly utilize ng-class. I only need to set it to true when clicked and other tab expressions should be set to false. Here's what I did to resolve the problem.

body{
    background-color: #e8e8e8;
    margin: 0;
    padding: 0;
}

.menu-content{
    padding: 30px;
    width: 100%;
    margin: 0 auto;
    text-align: center;
}

.menu-content button{
    background-color: dimgrey;
    color: #FFF;
    font-family: "Helvetica Neue", Arial, "Lucida Grande", sans-serif;
    font-size: 16px;
    border: 1px solid dimgrey;
    height: 35px;
    width: 100px;
}

.menu-content button:hover{
    color: gold;
    cursor: pointer;
}

.crud{
    padding: 30px;
    width: 90%;
    margin: 0 auto;
    text-align: center;
    background-color: #fff;
    border: 1px solid #aaa;
}

.active{
    color: gold !important;
    cursor: pointer !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="myApp" ng-controller="myController">
    <div class="menu-content">
        <button ng-click="activeClass('insert')" ng-class="{active: menu.insert}">Insert</button>
        <button ng-click="activeClass('view')" ng-class="{active: menu.view}">View</button>
        <button ng-click="activeClass('update')" ng-class="{active: menu.update}">Update</button>
        <button ng-click="activeClass('delete')" ng-class="{active: menu.delete}">Delete</button>
    </div>
    <div class="crud" ng-show="menu.insert">Insert</div>
    <div class="crud" ng-show="menu.view">View</div>
    <div class="crud" ng-show="menu.update">Update</div>
    <div class="crud" ng-show="menu.delete">Delete</div>
</div>

<script>
    (function(){
        var app = angular.module('myApp',[ ]);
        app.controller('myController', function($scope){
            $scope.menu = {};
            $scope.menu.insert = true;
            $scope.menu.view = false;
            $scope.menu.update = false;
            $scope.menu.delete = false;

            $scope.activeClass = function(tab){
                $scope.menu.insert = false;
                $scope.menu.view = false;
                $scope.menu.update = false;
                $scope.menu.delete = false;
                if(tab == 'insert') $scope.menu.insert = true;
                else if(tab == 'view') $scope.menu.view = true;
                else if(tab == 'update') $scope.menu.update = true;
                else $scope.menu.delete = true;
            }
        });
    })();
</script>

In my ng-class, this is what I did:

<div class="menu-content">
    <button ng-click="activeClass('insert')" ng-class="{active: menu.insert}">Insert</button>
    <button ng-click="activeClass('view')" ng-class="{active: menu.view}">View</button>
    <button ng-click="activeClass('update')" ng-class="{active: menu.update}">Update</button>
    <button ng-click="activeClass('delete')" ng-class="{active: menu.delete}">Delete</button>
</div>

Once again, thank you all :)

Answer №3

Instead of putting code in comments, I have decided to share it as an answer to make my point clearer.

    <div class="menu-content">
        <button ng-click="menu.selected = 'insert'" ng-class="{active: menu.selected == 'insert'}">Insert</button>
        <button ng-click="menu.selected = 'view'" ng-class="{active: menu.selected == 'view'}">View</button>
        <button ng-click="menu.selected = 'update'" ng-class="{active: menu.selected == 'update'}">Update</button>
        <button ng-click="menu.selected = 'delete'" ng-class="{active: menu.selected == 'delete'}">Delete</button>
    </div>
    <div class="crud" ng-show="menu.selected == 'insert'">Insert</div>
    <div class="crud" ng-show="menu.selected == 'view'">View</div>
    <div class="crud" ng-show="menu.selected == 'update'">Update</div>
    <div class="crud" ng-show="menu.selected == 'delete'">Delete</div>

Please note that the code has not been tested, but it should give you a good understanding of the concept.

This approach eliminates the need for additional bool variables and functions similar to an enum.

Extending this method would be much easier compared to the traditional bool approach.

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

Reset the text input field when the dropdown menu is set to 'no/other'

CURRENT: Choosing from a dropdown menu with options 'Yes' or 'No'. If 'Yes' is chosen: Display additional dropdowns/inputs for entry If 'No' is chosen: Conceal additional dropdowns/inputs WANT: I am looking to imp ...

What could be the reason for the CSS stylesheet not functioning properly on mobile devices?

I am a newcomer to web development and currently working on a website for a massage therapist using bootstrap. However, I am facing an issue where my CSS styles are not displaying correctly on mobile devices. The backgrounds and bootstrap navbar disappear, ...

Cannot locate AngularJS + Typescript controller

I'm encountering an error while attempting to integrate TypeScript with AngularJS. The issue I'm facing is: Error: [$controller:ctrlreg] The controller named 'MyController' has not been registered Does anyone have any insights on what ...

The aligning property "justify-content: space around" does not behave as expected on a line and does not provide the desired spacing

Below is the HTML code I am working on: <!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta na ...

Leveraging the power of AngularJS and Bootstrap, create a vertical nested tab interface that dynamically

After successfully creating a Dynamic Tab using AngularJS with Bootstrap, I decided to add Sub Tabs under one of the tabs dynamically. While this feature is working fine, I encountered an issue when trying to move to another main tab and then returning to ...

What sets npm install apart from manual installation?

I've been exploring requirejs recently. I'm trying to decide between installing it using npm install requirejs or manually downloading it from the website. Are there any differences between the two methods? Are there any advantages or disadvantag ...

Displaying complex JSON data in an HTML format using JavaScript

How can I convert the second array of entities into an HTML format from the JSON data using a for loop or similar method? To access the necessary data, I currently use console.log(data.response[0].entities.urls); $(document).ready(function () { $.getJSO ...

Tips on restricting dates to be equal to or earlier:

I have written a code to determine if two given dates are equal or not. The code should allow for the current date to be smaller than or equal to the provided date, but it should not allow for it to be greater. var date = '10-11-2015'; var toda ...

Angular sending information from one page and retrieving it on another

The reportForm page allows users to input information and submit it to create a report. reportData = { headline: $scope.headline, fromDate: $scope.fldFromDate, toDate: $scope.fldToDate, whatever: $scope.whatever } $http.post(reportUrl + $scope.repor ...

Incorporate an additional column into a table using AngularJS

I attempted to insert a new column upon clicking a button, but unfortunately, I was unsuccessful. I have created a JSFiddle demo to illustrate my issue. Any assistance in resolving this problem would be greatly appreciated. Below is my attempt: $scope.a ...

Ensure the cursor is continually grabbing while moving items within a list using the @angular/cdk/drag-drop functionality

I have an example on stackblitz where I am using @angular/cdk/drag-drop in my project. I am attempting to change the cursor to cursor:grabb and cursor:grabbing when the cursor is over an element and when I drag a picked element. Here is the CSS line I am ...

The swipe function of Hammer.js is unable to detect gestures on a rotated iframe

After creating a rotated iframe on the page using CSS transforms, I attempted to implement swipe events within the iframe. body.rotate iframe { transform: rotate(90deg); transform-origin: top right; position: absolute; t ...

Change the information displayed on buttons when clicked and provide options for users to navigate between different

In order to change the content when a button or number is clicked, you can utilize the buttons "1,2,3,4" or the Next and Prev buttons shown in the snippet. Both methods allow access to the same article. If you want to switch between articles using the Next ...

Synchronize two slideshows in a cycle with timed delays between each cycle

Is there a way to add a sequential delay between slideshows in the synchronized slide show example from cycle2 API? For example, having each div.cycle-slideshow start at 5s intervals (5s, 10s, 15s, 20s...). The cycle would then repeat with the first div st ...

What is the best way to conceal a new HTML5 element in Internet Explorer 8?

Here is an example of the code I'm working with: <div id="body-no-aside"> <div id="content"> Some contents </div> <aside id="aside"> Something aside </aside> </div> I have added html5shiv.js to ...

Tips for implementing page-break-after:always within a bootstrap row?

I have a bootstrap row with a set of divs inside like this: @media print { p { page-break-after : always } } <div class = "row"> <div> data1 </div> <p> break page here </p> <div> data2 </div> <div> ...

The Handsontable popup autocomplete editor is unfortunately truncated by the horizontal scrollbar

I have implemented an autocomplete feature on all columns in my project. However, I am facing an issue where the autocomplete editor gets cut off by the horizontal scrollbar. You can see the problem demonstrated in this jsfiddle link. Here is some code re ...

No matter how many times I modified the code in the ReactDOM.render() method within my index.js file, the end result remained unchanged

When I ran npx create-react-app my-app, and then proceeded to cd my-app and npm start, a browser opened on localhost:3000. While looking at the index.js file, I noticed that the ReactDOM.render() method included the following code: ReactDOM.render( <Rea ...

Trouble with refreshing view - angular, firebase

I've been struggling with getting this function to fire more than once, even though it should update when scope.job.getApplicants() changes. I've tried various methods like $watch, $apply, and firebase's ref.on('value', but nothing ...

Understanding AngularJS Directives: The Significance of Replace and Transclude

I'm looking for clarification on the following terms in relation to an AngularJS directive: replace: true / false and transclude: true / false Can someone provide a clear explanation? I've gone through the documentation but it's not com ...