Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.addClass not working on jqLite / Angular.js

I've been struggling lately to understand why the .addClass function was not working on jqLite

element.addClass('active')    

Element returns me an array of html elements, tested that over and over to be sure. I can hide(), show() , add a .css or get one, or even set .attr , but addClass resists me.

edit: element is a path in a svg block , and this is the reason that seems to make the addClass function irrelevant, still trying to fix it.

element is a jqLite object

Thank you.

like image 353
Nkogo Avatar asked Nov 10 '14 09:11

Nkogo


3 Answers

JqLite methods don't work with elements selected by plain javascript DOM selectors like querySelector or document.getElementById(). if you need so, first select it with 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 could use JqLite methods:
first example:

angElement.addClass('active');

second one:

myElement.addClass('active');
like image 169
Reyraa Avatar answered Nov 20 '22 06:11

Reyraa


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

the directive is quite simple to use..

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

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

like image 3
dinodsaurus Avatar answered Nov 20 '22 08:11

dinodsaurus


You have to use a 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 fiddle.

like image 2
Srinivas Paila Avatar answered Nov 20 '22 07:11

Srinivas Paila