How to handle click event in my class

I am trying to add a class to a clicked element and remove it when user clicks other elements.

I have something like

<li ng-repeat='test in tests' >
    <a href='' ng-click='pickTest($index, $event)'>{{test.title}}</a>
</li>

js

 $scope.pickTest = function(index, event) {
     $(event.target).addClass('blur');
     //this works when user clicks one of the <a> tags 
     //but I want to remove the class if user clicks another <a> tag
  };

How do I do this?

Thanks!

Answer

You can use ng-class to determine if the class needs to be appended based on a certain condition. Additionally, using $index in an ng-repeat is really not advisable because it pose problems when filters are applied in the ng-repeat directive. You can create two functions, isActive() for the ng-class directive and setActive() to set the active item.

angular.module('app', [])

  .controller('Ctrl', function($scope) {
  
    var activeTest = {};
  
    $scope.tests = [{
      title: 'Test 1'
    }, {
      title: 'Test 2'
    }, {
      title: 'Test 3'
    }, {
      title: 'Test 4'
    }];
  
    $scope.setActive = function(test) {
      activeTest = test;
    };
  
    $scope.isActive = function(test) {
      return angular.equals(activeTest, test);
    };
  
    	
  });
.blur {
  color: red;
}
<div ng-app="app" ng-controller="Ctrl">
  <ul>
    <li ng-repeat="test in tests">
      <a href="" ng-click="setActive(test)" ng-class="{blur: isActive(test)}">{{test.title}}</a>
    </li>      
  </ul>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Leave a Reply

Your email address will not be published. Required fields are marked *