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?

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

I'm guessing you could also use a scope variable for the object used in ng-class and a scope function for ng-click, also?
Yes you can do it like that as well, in fact it's easier to test that way.
This is exactly what I was looking for!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.