pedro luis pedro luis - 1 year ago 88
AngularJS Question

Angular directive is not adding css class to another element

Hi i am trying an angular directive changes the CSS of another element when a button is clicked,however despite the console.log shows me that the class was added, in the inspector still without the class.


.directive('openModal', function (Config) {

function link(scope, element, attrs) {
element.bind('click', function() {
var modal = angular.element(document.querySelector('#' + attrs.openModal)).css('display', 'block');
setTimeout(function(){ modal.className += ' modal-in'}, 10);
return {
restrict: 'AEC',
link: link

View which is called the directive

<header class="">
<div class="u-max-full-width">
<div class="row homehubusa-header">
<div class="one-third column">
<img src="./imgs/homehubusa.png" alt="logo homehubusa" class="logo"/>
<div class="two-thirds column">
<ul class="menu u-pull-right">
<a href="#">HomesUSA</a><span class="separator">&nbsp;</span>
<a href="#">Support</a><span class="separator">&nbsp;</span>
<a href="#">Contact Us</a>
<li class="callsign">
<a href="#" class="button button-danger" open-modal="modalLogin">Sign in</a>

Header Directive

.directive('appHeader', function (Config) {

function link(scope) {
scope.navLinks = [
{title: 'Home', href: 'home'},
{title: 'Help', href: 'seed-help'}
return {
templateUrl: Config.rootPath + 'shared/header/header-view.html',
link: link,
replace: true

The app structure

<body ng-app="App">
<app-header></app-header> /* This is the header directive, here is the button */
<div class="ng-view"></div> /* Here is the modal */

Joy Joy
Answer Source

You do not need to use timeout to make the CSS applied. Check a simplified example here: JSFiddle.

You'd better use addClass as it is supported by angular.element:

 link: function(scope, element, attrs) {
    element.bind('click', function() {
      var target = angular.element(document.querySelector('#test'));
      target.css('display', 'block');

For the display: block, I am doubting that your element #modalLogin is not there, because from my example, it is working: JSFiddle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download