ng-class will not activate a custom directive

I have developed a custom AngularJS directive that should work on elements with the specified class name .collapse.

However, when I apply this class using Angular's ng-class directive, the custom collapse directive does not get activated.

Here is a demonstration of the issue:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.welcome = "model";
    
    $scope.isTrue = function() {
      return true;
    }
});

app.directive("directive", function($compile) {
  return {
    restrict: 'C',
    scope: {
      model: '@'
    },
    link: function(scope, elem, attrs) {
      elem.css("background-color", "blue");
    }
  }
});
.directive {
  background-color: red;
  color: white;
  padding: 10px;
  margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <p>Simple Angular app</p>
  <div class="directive">Make my background color blue using the directive</div>
  <div ng-class="isTrue() ? 'directive' : ''">Make my background color blue using the directive</div>
</div>

Is there a way to ensure that the directive also functions on classes added through ng-class?

Answer №1

It seems like this question has already been addressed in more detail here.

In essence, the issue with ng-class setting the class too late after DOM load can be resolved by implementing a condition within the directive itself. The link provides examples of using attributes instead of classes for the directive and checking within the directive. Here is a sample code snippet demonstrating this:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore.js" type="text/javascript"></script>

<script>
var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        $scope.welcome = "model";

        $scope.isTrue = function() {
          return true;
        }
    });

    app.directive("directive", function($compile) {
      return {
            restrict: 'A',
            scope: {
                'condition': '='
            },
            link: function (scope, elem, attrs) {
            scope.$watch('condition', function(condition){
                if(condition){
                    elem.css("background-color", "blue");
                }
            });
        }
      }
    });
</script>

<style>
.directive {
  background-color: red;
  color: white;
  padding: 10px;
  margin-bottom: 10px;
}
</style>
</head>

<body>
<div ng-app="myApp" ng-controller="myCtrl">
  <p>Simple Angular app</p>
      <div class="directive" directive condition="true">Make my background color blue using the directive</div>
      <div class="directive" directive condition="false">DO NOT make the background blue because the condition is false</div>
      <div directive condition="isTrue();">Make my background color blue using a function for the the directive</div>
</div>
</body>

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

The chart refreshes whenever there is a change in the component's state

Whenever I click the button to use the changeState method, the state changes and the MoreInfo component appears. However, the chart is being drawn again as shown in this GIF: Below is the code snippet: import React from 'react' import './Ho ...

What is the best way to retrieve the rendered content through the `link` function of a directive?

Here is the code snippet below: <div class="test">{{name}}</div> This Angular code demonstrates how to alert the rendered string World: var app = angular.module('angularjs-starter', []); app.controller('MainCtrl', functi ...

Any ideas on how I can use PHP or JavaScript to repeatedly execute a segment of HTML code?

I recently tried using a for loop and heredoc in PHP with code that looks something like this: $options = ''; for($Year = date("Y"); $Year <= date("Y") + 5; $Year++) { $options .= "<option>$Year</option>\n"; } $Select = ...

Changing JavaScript functions into jQuery functions

Currently, I have this Javascript function that I am interested in converting to jQuery: function confirm() { var http = new XMLHttpRequest(); var url = "index.php?tag=' . $dt . '"; var params = "confirm_ref=' . urlencode(encry ...

Tips for handling arguments in functional components within React applications

Is it possible to pass arguments to a function in a functional component without creating the function directly in JSX? I've heard that creating functions in JSX is not recommended, so what's a better way to achieve this? function MyComponent(pr ...

"Is it possible to include a button for horizontal scrolling in the table

I have a bootstrap table with overflowing set to auto within its container, along with a locked first column. While a horizontal scroll bar allows for viewing additional data, I am looking to incorporate buttons for navigation as well. Users should have th ...

Tips for implementing two Secondary Actions in React Material UI, with one positioned on the left corner and the other on the right, while ensuring that the behavior of the

Is there a way to display two secondary actions on either end of a list item without triggering additional onclick events? The placement can be adjusted by overriding the CSS properties right and left. https://i.stack.imgur.com/rhr7N.gif The issue arises ...

Using Javascript to dynamically add rows to a table, however they mysteriously appear and disappear soon

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserPermisson.aspx.cs" Inherits="TestProjects.UserPermisson" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" ...

Grunt integration for version control

After sticking to simple Html and Css for the longest time, I'm finally diving into JavaScript for a new project where I want to automate versioning. I've been following the SemVer Guidelines and my projects are currently versioned as "version": ...

What are the steps to creating a versatile HTTP service in AngularJS?

In my Angular module, I created a universal HTTP handler for all my AJAX requests. I thought that I could use this service across multiple controllers, but I encountered an issue where the promise seems to be shared globally. When ControllerOne utilizes ...

File index with Node.js server for handling files

I currently have a code snippet for setting up a file server that serves files from a static folder named "public1". However, I am facing difficulties in making an HTML page display by default when a user navigates to the IP address in a browser. Although ...

What is the best way to change a variable in an AngularJS view?

My Request In my application, I have implemented 3 views, each with its own controller. The first view is the home screen, and from there the user can navigate to view 2 by clicking on a div element. On view 2, the user can then move to view 3 by clicking ...

Performing Vue CLI Global Upgrade

Struggling to create a new Vue.js project using the Vue CLI service, I encountered an error. With @vue/cli-service 3.0.0-beta.7 installed (confirmed by running vue -V), attempting to start a new project triggered the following error: ...

Preventing Users from Accessing a PHP Page: Best Practices

I'm currently focusing on a problem that involves restricting a user from opening a PHP page. The following is my JavaScript code: <script> $('input[id=f1email1]').on('blur', function(){ var k = $('inp ...

The preflight request for OPTIONS is receiving a 400 bad request error on the secure HTTPS

When making an Ajax call on the front end and calling a WCF service through Ajax, I encountered an issue with adding headers. As a result, a preflight OPTIONS request is triggered but fails due to the URL being blocked by CORS policy. I tried adding the f ...

Can we verify if this API response is accurate?

I am currently delving into the world of API's and developing a basic response for users when they hit an endpoint on my express app. One question that has been lingering in my mind is what constitutes a proper API response – must it always be an o ...

Indicator malfunctioning on Carousel feature

I created a carousel containing six photos, but I am encountering an issue with the carousel indicators below. The first three indicators work correctly – when clicked, they take me to the corresponding slide (e.g., clicking the 1st indicator takes me ...

The issue of duplicate results appearing in the Wikipedia viewer persists even after conducting a second search

I have been working on a project to create a wiki viewer, but I've encountered an issue. Currently, I am utilizing the Wikipedia API. When a user enters a search query, they are presented with 5 possible articles (title and first sentence), and upon ...

What is the purpose of returning a function in a React Hook?

Currently, I am incorporating Material-UI components into my project and have implemented the AutoComplete component in my application. While exploring an example provided by the Material-UI team, I stumbled upon a fascinating instance of using Ajax data ...

Ensure that clicking on various links will result in them opening in a new pop-up window consistently

I am facing an issue with my HTML page where I have Four Links that are supposed to open in separate new windows, each displaying unique content. For instance: Link1 should open in Window 1, Link2 in Window 2, and so on... The problem I'm encounter ...