Get and set an element class in AngularJs

I added the ng-click icon to my icon as follows:

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

And here is 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 get the error "elem.getAttribute is not a function". Trying to switch the "class" to "ng-class", I ran into another problem: "ng-class" is not recognized by my css files.

Is there a way to get / set the "class" attribute directly?

0
source share
4 answers

Try the 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> 

Additional Information angular.element

+2
source

You can use the classList property , which is native and can help you a lot:

 div.classList.remove("foo"); div.classList.add("anotherclass"); div.classList.toggle("visible"); console.log(div.classList.contains("foo")); 
+2
source

Try this code below instead of yours

 var elem = obj.target.attributes.class.value; 

Also why is ng-class not working for you? It should work, I think you may not match your CSS file.

+1
source

elem is an array, so you need to use elem [0]:

 $scope.processForm = function(obj) { var elem = angular.element(obj.currentTarget);// or angular.element(obj.target); alert("Current class value: " + elem[0].getAttribute("class")); }; 
+1
source

All Articles