1

Before I knew about things like Angular and jQuery, there was plain old 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 used this in the past to toggleClass name in an onclick event like so:

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

Here is a working JSFiddle.

How would I implement this as a directive in Angular?

nhuff717
  • 369
  • 2
  • 3
  • 17

2 Answers2

2

You can use AngularJs' ng-class directive instead of creating another 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>
ryeballar
  • 29,658
  • 10
  • 65
  • 74
1

Angular is not jQuery, so your thought process should not be about adding removing classes or showing hiding elements or anything to do on these lines.

Please refer to this SO post for some good pointers "Thinking in AngularJS" if I have a jQuery background?

In Angular model drives the view.

What you are doing should be done using the standard ng-class directive.

Let's say you have a grid of users and you want highlight rows when the user click on the row signifying the user has been selected. The way you would go about it would be to define the row html as

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

Now the state of user.selected drives the view and toggles the class on every click.

Community
  • 1
  • 1
Chandermani
  • 42,589
  • 12
  • 85
  • 88