Adding class to an element on its click event

Sajith picture Sajith · Oct 21, 2013 · Viewed 58.9k times · Source

I am new to Angular Js. I need to add a class to an element on its click event. I tried the following code. But it is not working.

<html>
<head>
    <style>
        .active{color:red;}
    </style>

    <script src="js/lib/jquery.min.js"></script>
    <script src="js/lib/angular.min.js"></script>
</head>
<body ng-app="MyApp" ng-controller="MyController">

    <div ng-repeat="data in datas">
        <p ng-click='selectMe()'>{{data.name}}</p>
    </div>

    <script>
    var app = angular.module('MyApp',[]);
    app.controller('MyController',function($scope){
         $scope.datas = [{name:"first"},{name:"second"}];

         $scope.selectMe = function (){
            $(this).addClass('active');
         }
    });

    </script>
</body>
</html>

What is the problem in this code? Is it necessary to use ng-class ? How to do it?

Answer

huston007 picture huston007 · Oct 21, 2013

You can pass $event to click

<p ng-click='selectMe($event)'>{{data.name}}</p>

//code:
$scope.selectMe = function (event){
   $(event.target).addClass('active');
}