.addClass does not work with jqLite / Angular.js

I've been struggling lately to understand why the .addClass function didn't work on jqLite

element.addClass('active') 

The element returns an array of html elements to me, checked it again and again to be sure. I can hide (), show (), add .css, or get one, or even set .attr, but addClass resists me.

edit: element is the path in the svg block, and for this reason the addClass function does not matter, is still trying to fix it.

element - jqLite object

Thanks.

+5
source share
3 answers

JqLite methods do not work with elements selected using simple javascript DOM selectors like querySelector or document.getElementById() . if you need it, first select it using javascript selectors, then wrap it in angular.element :

 var element = document.querySelector('a[target="_blank"]'); var angElement = angular.element(element); 

or simply

 var myElement = angular.element( document.querySelector('a[target="_blank"]') ); 

then you can use JqLite methods:
first example:

 angElement.addClass('active'); 

second:

 myElement.addClass('active'); 
+22
source

I think this is generally a bad idea ... Adding classes to angular is usually not done in jquery style, you should use the ng-class directive https://docs.angularjs.org/api/ng/directive/ngClass

The directive is pretty easy to use.

 <div ng-class="{active: show}"></div> 

This div will get the class active if $scope.show is true

+3
source

You need to use the directive to add and remove classes

HTML:

  <div ng-controller="MyCtrl"> <input type="button" active value='One' /> <input type="button" active value='Two' /> <input type="button" active value='Three' /> </div> 

JS:

  var app = angular.module('myApp',[]); app.directive('active', function() { return { link: function(scope, element, attrs) { element.bind('click', function() { //Remove the active from all the child elements element.parent().children().removeClass('active'); //Add active class to the clicked buttong element.addClass('active'); }) }, } }); function MyCtrl($scope) { } 

Here is the link to the script.

+2
source

Source: https://habr.com/ru/post/1206551/


All Articles