Chernogorskiy Fedor Chernogorskiy Fedor - 2 months ago 11
AngularJS Question

Get and Set class of an element in AngularJs

I've added the ng-click to my icon like this:

<img src="images/customer_icon.png" class="customer" ng-click="processForm($event)">


And here's the js-file.

var app = angular.module('myapp', []);
app.controller('mycontroller', function($scope) {
$scope.processForm = function(obj) {
var elem = angular.element(obj);
alert("Current class value: " + elem.getAttribute("class"));
};
});


I'm getting the "elem.getAttribute is not a function" error. Trying to switch "class" to "ng-class", i faced another problem: "ng-class" is not recognised by my css files.

Is there any way I can get/set the "class" attribute directly?

Answer

Try following snippet.

var app = angular.module('myapp', []);
app.controller('mycontroller', function($scope) {
    $scope.processForm = function(event) {
      var element = angular.element(event.target);
      //Old Class
      console.log("OLD CLASS : " + element.attr('class'));
      element.removeClass('customer').addClass("newClass");
      //New Class
      console.log("NEW CLASS : " + element.attr('class'));
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="mycontroller">
<img src="http://placehold.it/200x100" class="customer" ng-click="processForm($event)">
</div>

More information angular.element