Home Ask Login Register

Developers Planet

Your answer is one click away!

David Soler February 2016

Add and remove class when element clicked with Angular

I would like to know how to add or remove a class to an HTML element when a div is clicked with AngularJS. I have a div that when clicked I need to check if it includes a class('already-member') or not. If the class exist, then remove it, and if it does not, then add it. I know how to do this in Javascript but not sure in Angular.


<div collection-repeat="friend in user.friends" item-width="50%" item-height="80px" class="friends-list">
  <div class="item friend-avatar" ng-class="{'already-member' : friend.already_member == true}" ng-click="toggleStatus()">
    <div class="avatar">
      <img src="{{friend.avatar_url}}">
      <i class="check-icon" ng-class="{'hidden' : friend.already_member == false}"></i>
    <div class="wrapper-friend-name">
      <p class="friend-name">{{friend.name}}</p>

this is the code in controllers.js

.controller('MembersCtrl', function($scope) {
  $scope.members = [
    {avatar_url: "http://..."},
    {avatar_url: "http://..."},
    {avatar_url: "http://..."},
    {avatar_url: "http://..."}
  $scope.user = {
    avatar_url: "http://...",
    friends: [
      {avatar_url: "http://...", name: "Pablo Pepunto", already_member: true},
      {avatar_url: "http://...", name: "Pablo Pepunto", already_member: false},
      {avatar_url: "http://...", name: "Pablo Pepunto", already_member: false},
      {avatar_url: "http://...", name: "Pablo Pepunto", already_member: false}
  $scope.$on('$ionicView.beforeEnter', function (event, viewData) {
    viewData.enableBack = true;
  $scope.toggleStatus = function($scope) {
    console.log('$scope'); //$scope is undefined
    $scope.already_member = !$scope.already_member;



Martin Golpashin February 2016

  1. Add a ng-click Listener on your div element. When the click is triggered, toggle a boolean variable isMember in your controller to set the class.
  2. Use the ng-class directive with your isMember variable on your div to check whether isMember is set or not: ng-class="{'already-member': isMember}"

You could also set and use the variable directly like this:

<div ng-click="isMember = !isMember" ng-class="{'already-member': isMember}">

I recommend setting the flag in your controller for better readability.

FlorianTopf February 2016

I would do the following:

In the template:


In the controller:

$scope.toggleStatus = function(friend) {
    friend.already_member = !friend.already_member;

Then the ng-class="{'hidden' : friend.already_member == false}" directive you defined should work.

Post Status

Asked in February 2016
Viewed 3,801 times
Voted 7
Answered 2 times


Leave an answer

Quote of the day: live life