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

Bootstrap columns causing a collision

My website has a problem when viewed on mobile at 320 x 480 resolution. Two columns filled with text collide and mash up the text together. I initially tried without using columns, just "container-clearfix," but that did not resolve the issue. Check out t ...

Incorporate geographical data from a JSON file into my Google Maps application

Hey there, I'm a newbie on this forum and could really use your expertise. I've put together an html5 page with Google maps using the API key from Google (My code is shown below), it's working fine with a central marker in place and loads pe ...

Issue with ASP.NET Base64 image source rendering incorrectly

After retrieving a Base64 string from Azure active directory using a Lambda function, which represents a user's profile picture, I am facing issues displaying it on an ASP.NET page. Below is the code snippet in ASP.NET (The referenced HTML object is ...

How to write a unit test for a factory in AngularJS using Karma?

Currently, I am developing a basic AngularJS 1.x web application. Here is a breakdown of my project structure: main.js: var app = angular.module('app', []); factory.js app.factory('DataFactory', function(){ var DataService = {}; ...

Utilize a while loop in JavaScript to trigger a message when a variable dips below zero

Forgive me if I seem clueless. I am a beginner in the world of Javascript and am currently experimenting with loops. At the moment, I am toying around with this particular piece of code: <!DOCTYPE html> <html> <body> <button oncl ...

In Internet Explorer 8, angular's $window service may sometimes return undefined

I've developed a custom directive called slideshow with some scope variables that are two-way bound to ng-style. This directive functions as a responsive carousel that adjusts based on the window height retrieved using the $window service. During tes ...

Creating a Conditional Structure in HTML: A Step-by-Step Guide

My website is in need of a form that can identify the user's role based on their name input. This feature is essential for individuals with private roles. Is it possible to achieve this using HTML alone, without relying on JavaScript? If not, what st ...

Step-by-step guide on retrieving news_id and displaying it in an alert when an item

How can I retrieve the item ID when it is clicked in a Listview to display the specific news_id in an alert? Below is the HTML code snippet for my page: <body> <div data-role="page" id="taxmanhomepage" data-theme="e"> <div data-role="h ...

Adding content to an empty element will not produce the desired result

I'm trying to show each character of a string, which is stored in an array, one at a time. However, when I use threadsleep(a) with the code found here: http://jsfiddle.net/thefiddler99/re3qpuoo/, all the characters are displayed at once. There seems t ...

When creating a new user with 'Add new user' function in AngularJS, the JSON data overrides the existing data instead of being added separately. This issue needs

I have recently started using AngularJS and encountered an issue when trying to send form data to a JSON file after clicking the 'Add New Member' button. The new JSON data overwrites the existing data, but I actually want it to be added after the ...

When inserting the HTML of a webpage into an iframe, the displayed content may vary slightly from the original page

I am facing an issue with my webpage where I extract the html, transmit it via websockets using socket.io to another page containing an empty iframe, and then inject the html dynamically into the iframe. My code for injecting the html looks like this: fr ...

Linking the location of the pop-up to the currently selected text box

I am currently experimenting with setting the top and left values relative to the selected_element (which is active at the time of triggering the popup) in a manner similar to a tooltip. I attempted to use $().position() in combination with jQuery, but it ...

What is the best way to determine if a date is empty using Vuetify?

Could someone help me with checking if a date was entered by the user? I want to display an error message if a date is not provided. I attempted to use a rule for this purpose, but unfortunately it's not showing any error message. Below is the code I ...

The Tab style in Mobile Angular UI does not get applied correctly when nested within an ng-repear

While working on a tabbed control with mobile-angular-ui (), I encountered an issue when trying to generate the tabs dynamically. Initially, everything looked good with the following code: <ul class="nav nav-tabs" ui-state='activeTab' ui-def ...

Breaking the line when combining an image_tag and text in a Rails navbar

Looking for some help combining a logo and brand name in my Bootstrap navbar. I'm running into an issue where there is a line break separating the logo and text. Can someone provide some assistance? <%= link_to image_tag("brand_logo.png") + " Bran ...

What is the best way to achieve line breaks in text that auto-wraps in JavaScript/PHP?

My resizable div contains text/sentences. As I adjust the size of the div, the text wraps itself to perfectly fit within the available space in the container div. Now, I am faced with the task of converting this dynamic text into an image using php and th ...

How to incorporate a delay in ng-repeat using AngularJS

Currently, I am facing an issue with my ng-repeat block. In this block, I am generating elements based on data received from an ajax request, which sometimes causes a delay due to latency. Within the same block, I have implemented a filter to remove unwant ...

How to accentuate search results using Angular filters and conceal non-matching text?

Recently, I came across an interesting example of using Angular filter to highlight search results. It works well in highlighting the word 'suit', but I noticed that all non-matching text remains visible. If you'd like to see the example I ...

What is the best way to distinguish between a button click and a li click within the same li element

In my angular and css GUI, each line is represented as an li inside a ul with a span. The functionality includes a pop-up opening when clicking on the li background and another action occurring when pressing the button (as intended). The issue arises when ...

The lack of responsiveness in Bulma CSS is causing issues with the Bulma Carousel and image displays

I recently built a website using the Bulma CSS framework for styling, incorporating the Bulma Carousel for a text carousel. Utilizing Bulma's column feature, I positioned the carousel next to an image/video on the left side of the screen. Everything l ...