Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding class to an element on its click event

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?

like image 810
Sajith Avatar asked Oct 21 '13 11:10

Sajith


1 Answers

You can pass $event to click

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

//code:
$scope.selectMe = function (event){
   $(event.target).addClass('active');
}
like image 165
huston007 Avatar answered Oct 19 '22 23:10

huston007