A function in AngularJS called ng-click that applies a class to a selected navigation link when clicked

I'm having trouble figuring out the correct code for a navigation sidebar in an angularJS app. The goal is for the active link to be highlighted with a background color when clicked. Currently, it does work but the highlight only shows up after clicking each link twice. What am I missing here? Any assistance would be highly appreciated.

javascript

 $scope.addActiveClass = function ($index) {
        $scope.addActiveClass = $index;
        var checked = $('ul.sidebar2-nav li');

        $(checked).on("click", "", function () {
            $(this).addClass('active-label');

        });
     }

html

<nav id="program-editor-pullout" menustate="closed" >
        <ul class="list-unstyled sidebar2-nav">
            <li ui-sref-active="active-label">
                <div class="checkbox">
                    <label>
                        <input type="checkbox" ng-checked="true">
                        <a ng-click="addActiveClass($index)" ng-class="{active: home}" ui-sref-active="active" ui-sref=".home">Home</a>
                    </label>
                </div>
            </li>
            ...
            <li ui-sref-active="active-label">
                <div class="checkbox">
                    <label>
                        <input type="checkbox" ng-checked="true">
                        <a ng-click="addActiveClass($index)" ng-class="{active: documents}" ui-sref-active="active" ui-sref=".document">Documents</a>
                    </label>
                </div>
            </li>
        </ul>
    </nav>

CSS

  ul.sidebar2-nav li a.active {
   color: #000;
   cursor: pointer;
   text-decoration: none;
   }
  ul.sidebar2-nav li.active-label {
   background: whitesmoke;
  }

Answer №1

After some investigation, I managed to find a solution to my issue. Although your example was accurate, upon further inspection of my HTML code, I noticed the following:

<li ui-sref-active="active-label" ng-click="addActiveClass($event, $index)">
        <div class="checkbox">
            <label>
                <input type="checkbox" ng-checked="true">
                <a ng-class="{active: home}" ui-sref-active="active" ui-sref=".home">Home</a>
            </label>
        </div>
    </li>

Upon closer inspection, I realized that the ng-class and ui-sref-active attributes were placed on the anchor tag. I made the necessary adjustments by removing these attributes, resulting in the desired functionality. I extend my gratitude for your valuable guidance in navigating through this issue!

Answer №2

Transfer the click event from element 'a' to its parent 'li' tag

<nav id="program-editor-pullout" menustate="closed" >
            <ul class="list-unstyled sidebar2-nav">
                <li ui-sref-active="active-label" ng-click="addActiveClass($event, $index)">
                    <div class="checkbox">
                        <label>
                            <input type="checkbox" ng-checked="true">
                            <a ng-class="{active: home}" ui-sref-active="active" ui-sref=".home">Home</a>
                        </label>
                    </div>
                </li>

Update the click handler to the following

$scope.addActiveClass = function ($event, $index) {
        $scope.addActiveClass = $index;
        //var checked = $('ul.sidebar2-nav li');

        //$(checked).on("click", "", function () {
        //    $(this).addClass('active-label');

        //});

        $($event.target).addClass('active-label');
     }

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

What causes the console.log function to behave in this manner?

When using the node.js interpreter, if you run the code: console.log("A newline character is written like \"\\ n \"."); //output will be:- // A newline character is written like "\ n ". However, if you just enter the following in ...

Setting up Apache's mod_proxy for handling ProxyPass and ProxyPassReverse to facilitate cross-domain ajax requests

I'm currently developing an HTML5-JavaScript mobile app using PhoneGap and need to interact with a REST service. The REST service is hosted at "http://localhost:8080/backend/mvc/" My development environment consists of a WAMP server (Apache2) at htt ...

CSS is not being applied to the HTML select element generated by PHP

Issue Update: The problem I'm facing is not related to dynamic generation, but rather the sheer number of items. To see a demo, click here: plunker I have select boxes on my website with a consistent style: dark background with white text. select { ...

Personalizing Twitter Bootstrap Directly from the Bootstrap Source Directory

As I work on developing a responsive web application using Twitter Bootstrap, my goal is to customize the Bootstrap framework to fit my specific needs. To do so, I have downloaded the Bootstrap source files from getbootstrap.com. My plan is to customize B ...

Guide on converting data from PHP to JSON using JavaScript

Here is some data that I need to loop through: image1 url1 description1 image2 url2 description2 image3 url3 description3 image4 url4 description4 image5 url5 description5 After looping through the data: var imagesDataArray = [ { src: &apo ...

Shade of a row within a PHP table

I have a table that is populated with data from a database. Is there a way for me to dynamically change the color of a row based on certain conditions from a JSON file? For example, if the temperature exceeds a set minimum value, I want to highlight the ro ...

Styling multiple checkbox items in an Angular Material Autocomplete

Is there a way to adjust the height of autocomplete multiple checkbox items in Angular Material? I'd like it to look like this With a line item height of 18px But instead, it looks like this when using multiple checkboxes With a different checkbox ...

Is there a way to undo the transition when hovering out?

Is it possible to achieve a reverse transition animation on hover out using CSS? I want the "Menu" text to slide to the right blue line when I hover out, and after a delay of 400ms, slide back from the left grey line. Can this be done? .menu { displ ...

Expand Elements to occupy entire width

My CSS skills are still in the early stages. I haven't delved too deeply into it. I have a query regarding how to achieve full width for an element. I've included my code below, but the basic approach I tried using 'width: 100%' didn&a ...

Switch between adding elements to various div containers

Can we implement a functionality where clicking an anchor tag moves the .item from .region1 to .region2, and then moving it back to .region1 when clicked again? Essentially creating a toggle behavior? <a href="#" class="btn">Click</div> &l ...

Using TypeScript with React: Initializing State in the Constructor

Within my TypeScript React App, I have a long form that needs to dynamically hide/show or enable/disable elements based on the value of the status. export interface IState { Status: string; DisableBasicForm: boolean; DisableFeedbackCtrl: boolean; ...

Keep things in line with async functions in Node JS

Hello, I am just starting out with NodeJs and I have a question. I am trying to push elements into an array called files based on the order of the urls provided, but it seems like I'm getting a random order instead. Below is the code I've been wo ...

Encountered an issue retrieving audio during recording with Recorder.js

I've come across a scenario where I'm utilizing the Recorder.js Demo for recording audio. Interestingly, it works perfectly on Linux but encounters an issue when used on Windows. A pop-up alert stating "Error getting audio" shows up. Here's ...

Is it feasible to assess JavaScript expressions during compilation using Webpack?

I'm currently in the process of setting up webpack for a new project. This project is quite extensive and available in multiple languages. I am aiming to have each entry point in my project be represented by separate files in each language. The catch ...

How to reference color variables from code behind in ASP and use them in CSS files

I have a total of 3 files dedicated to my Login-Screen: Login.aspx, Login.aspx.cs, and LoginStyle.css Upon the execution of the Page_Load method, I retrieve various data from the current system, including the theme-color represented as a string (e.g., #00 ...

What is the process for getting the input value when a key is released?

My goal is to capture the actual value or text from an input field and store it in a variable. However, when I use the console to check the output, it shows me a number indicator that increments each time I type something. <input id="usp-custom-3" ty ...

Adjust Mui Autocomplete value selection in real-time

I have implemented Mui AutoComplete as a select option in my Formik Form. <Autocomplete disablePortal options={vendors} getOptionLabel={(option) => option.vendor_company} onChange={(e, value) => {setFieldValue("vendor_id", value. ...

Revamping the login interface for enhanced user

Whenever I attempt to login by clicking the login button, there seems to be an issue as it does not redirect me to any other page. Instead, I am left on the same page where I initially clicked the button. The intended behavior is for users to be redirected ...

Error encountered using jQuery $.post: TypeError - e.type is not a valid function

I'm currently in the process of developing a feedback script specifically for the ZetaBoards forum software. My approach has been to create a $.post function, but when I attempt to submit the form by clicking the submit button, all I get in return is ...

How can I loop through ajax data and assign it to the @foreach loop within the same view in a Laravel application?

I need to implement filtering functionality in a table view, where the data displayed can be updated based on user-selected options. The goal is to refresh only the table part when a search option is chosen from the filters, displaying the new filtered d ...