What would be the best way to implement a toggleClass feature within an AngularJS directive?

Long before discovering Angular and jQuery, my go-to was good old plain Javascript like this:

function toggleClass(e, c) {
    var classes = e.className.split(' ');
    var match = false;
    for(var i=0; i<classes.length; i++) {
        if(classes[i] === c) {
            match = true;
            classes.splice(i,1);
            break;
        }
    }
    if(!match) classes.push(c);
    e.className = classes.join(' ');
}

I've utilized this in the past to toggle a class name within an onclick event like shown below:

<div onclick="toggleClass(this,'foo')"></div>

Check out this functional JSFiddle.

Now, how can I convert this into a directive in Angular?

Answer №1

If you want to style elements dynamically in AngularJs, consider using the ng-class directive instead of creating a new directive.

angular.module('demo', [])

  .controller('Ctrl', function($scope) {
     $scope.toggleRed = true;
  });
.box {
  padding: 50px;
  display: inline-block;
  background-color: #efefef;
}

.box.red-box {
  background-color: red;
}
<div ng-app="demo" ng-controller="Ctrl">
  
  <div class="box" 
       ng-class="{'red-box': toggleRed}" 
       ng-click="toggleRed = !toggleRed">Click Me</div>
  
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Answer №2

Angular operates differently from jQuery, so focusing on adding or removing classes and showing or hiding elements is not the way to approach it.

If you come from a jQuery background, you may find some useful insights in this Stack Overflow post: "Thinking in AngularJS" if I have a jQuery background?

In Angular, the model dictates how the view behaves.

To achieve what you need, use the standard ng-class directive.

For example, imagine you have a grid of users and you want to highlight rows when a user clicks on them to indicate selection. You can define the row's HTML like this:

<tr ng-repeat='user in users' ng-click='user.selected=!user.selected' ng-class={'active': user.selected}>
</tr>

Now, the state of user.selected controls the view and toggles the class with each click.

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

Execute code after selecting the link

To simplify my question, I will provide an example: Suppose I have two sample pages that I want to demonstrate: Page 01 <script> var demo = 'X1'; alert(demo); $( document ).ready(function() { $("#cont").on("click" ...

Hide the drawer when a user clicks on a currently selected tab

Just starting to explore Material-UI and React here, so please bear with me if I'm making any rookie mistakes. :) I've set up a Drawer component containing a Tabs element with multiple Tab components inside. It's nothing too fancy yet - mos ...

JavaScript Error - Unable to access 'getChartLayoutInterface' property of undefined in Google Charts

Recently, I came across an issue where I received a console error stating: Cannot read property 'getChartLayoutInterface' of undefined After researching similar questions, it seems that the error is due to the Google Visualization API not loadi ...

Embed a div element within a content-editable area

Is there a way to add a div with text to a contenteditable element and automatically select the text between the div tags after inserting the div? div.innerHTML +='<div id="id">selecttext</div>' I have tried this method, but it does ...

Using Javascript/jQuery to show measurements in the format of feet and inches

I am currently developing a BMI calculator and facing an issue. I would like the height, which is in inches, to be displayed in feet and inches format. Additionally, I want the weight in pounds to be shown in stones and pounds. Here is the code snippet I ...

Switch Button Color in React Upon Adding to Favorites

Currently, I am facing a challenge with displaying a list of items and allowing users to add items to their Favorites. The problem lies in the fact that I am only capturing one favorite state. As a result, when a user clicks on one button, all item button ...

What is the best way to retrieve user input from an HTML form and save it into a preexisting JavaScript array?

I have a form that needs to capture user input and save it as an array in JavaScript. Here is the form: <form id="contractFormForm"> Contract Reference: <br> <input type="text" name="contractref" id="contractref"> <br&g ...

To ensure the react page is not rendered until the script has finished executing, follow these steps in React

Upon fetching data from an API using my script, I encounter a challenge where the react page loads before the script finishes loading. As a result, I end up with a page lacking necessary information and have to refresh in order to see the updates. The ma ...

AngularJS and Ionic Framework - Click on a specific row to interact with it

I am struggling to open a new page when an item is touched in my HTML code. Despite trying multiple times, I can't seem to make it work and I'm at a loss as to why. Below is the snippet of my HTML: <!DOCTYPE html> <html> <hea ...

Can you explain the significance of the '.' in the state name within the AngularJS state provider?

Why is the '.' significant in state('xxx.yyy') within Angularjs 1.x? Q1) Are the 2 states emAllTickets.closed and emAllTickets/closed different? What is the significance of . and / in this context? Q2) If I have HTML code that routes ...

Using Raycaster in ThreeJS to pick out faces from models loaded with STL Loader

I am currently developing a .stl viewer using Three.js with the objective of selecting and calculating specific areas within the model. To achieve this area calculation, I need the capability to select faces (e.g. change color). Although I came across som ...

How to incorporate and separate JavaScript syntax for individual objects

Here is the data I have: const data = [ { date: '2018-04-11T00:00:00.000+07:00', price: 5000 }, { date: '2018-04-03T00:00:00.000+07:00', price: 2000 } ] I am attempting to incorporate moment.js syntax to format the date, ...

Can one button be clicked to trigger the activation of another button through a click?

Just as the title suggests, I am wondering how to make this happen? Any guidance would be greatly appreciated! $('.notVisible').click (function(){ alert("I'm the invisible button") }); $('.visible').click (function(){ al ...

Error: Rails javascript_include_tag is expecting one argument, but received two (2 for 1)

Every time I try to add my manifest application.js file to the main layout, I keep getting this argument error. <!DOCTYPE html> <html> <head> <%= csrf_meta_tags %> <%= javascript_include_tag "application" %> </head> & ...

The drop-down list was designed with a main button to activate it, but for some reason it is not functioning properly. Despite numerous attempts, the list simply will not display as intended

<html> <body> <button onclick="toggle()" class="nm" > main</button> <div class="cntnr" style="display : none;"> <ul class="cnkid"> <li class="cnkid"><a class="cnkid" ...

Implementing a jQuery event listener for an event that requires another event as a parameter

My goal is to trigger the function scheduleAdd when the enter button is pressed, but only if an input with the id 'addSchedule' is currently in focus. This is what I have so far: $('#addSchedule').focus(function(e) { var evt = ...

Having trouble locating the bootstrap import statement

Currently, I am working on a project in Angular where I have defined two styles in the angular.json file - styles.css and node_modules/bootstrap/dist/css/bootstrap.min.css. After running ng serve, it shows that it compiled successfully. However, upon ins ...

Encountering issues when integrating AngularUI with Bootstrap 3 wiring

I've been struggling to integrate AngularUI with Bootstrap 3 without success. I copied the necessary AngularUI code from the bootstrap 3 branch found here: https://github.com/angular-ui/bootstrap/tree/bootstrap3_bis2 For my first attempt, I decided t ...

Change the name of a file to a name chosen by the user while uploading it to an

I'm a beginner when it comes to node.js and I'm facing an issue that I couldn't find a solution for despite looking into various related topics. My problem involves using Node.js on the server side to upload a file and rename it based on a ...

Traverse through an array or object using recursive render functions in JavaScript

Here is an example of the issue I am currently trying to solve: https://codepen.io/wombsplitter/pen/KyWKod This is the structure of my array: [{ //obj 1 link: [{ //obj 2 link: [{ //obj 3 }] }] }] The ...