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?
The Angular way (MVVM actually) to do this is to update the model through the click event and then paint according to the model, e.g.:
And the HTML:
I know this is an old question but just came across it and think there's a simpler answer to any of the ones given here:
No code needed in the controller other than to create your
datas
array. This works because theactive
variable is created within the child scope of eachdiv
created by the ng-repeat rather than in the controller's scope.I've created an updated version of @joshwhatk's codepen here
One of the best way is
Not required any code in controller
More Info
You can pass $event to click
I know this question already has an answer, but I was shocked when I realized that the chosen best answer (which I had already implemented in some of my code) doesn't align with the AngularJS documentation.
According to AngularJS Documentation:
huston007's answer works great, however, it does not follow this recommendation.
With this as your data input:
And this your html:
My suggested solution uses an array of objects with the person's id as the key and a booleon as the value. This is linked to in the DOM through the ngClass directive.
You can check out my codepen here.
I also have another version that removes all of this logic from the controller, leaving only the variable definition, but I thought that might be out of the scope of this question. (codepen.io/joshwhatk/pen/bwmid)
Hope this helps.