Toggle two classes with AngularJS / jqLite on click

966 Views Asked by At

I wan't to get a slideIn / slideOut animation by toggling the classes slideInRight and slideOutRight to a ul element.

I've tried it in different ways but I it only works with one className.

How can I add the class slideInRight on the first, and the class slideOutRight on the second click on my ul element with the class dropdown-menu?

I've tried it this way:

angular.element('.dropdown-toggle').on('click', function(){
    angular.element('ul.dropdown-menu').toggleClass('slideOutRight slideInRight');
});

What am I doing wrong?

Hope you can help.


UPDATE:

Here is a Plunker of the current state of my code. This way only the slideInRight animation works. If I click the button again, the ul disappears without the slideOutRight animation.

What's wrong?

2

There are 2 best solutions below

2
On

You may want to try using angular's ng-class?

I'm sort of new to angular, but the way I did it was like this:

<ul class="dropdown-menu" ng-class="ulOpen ? 'slideOutRight' : 'slideInRight'">

and the js

angular.element('.dropdown-toggle').on('click', function(){
    if($(this).hasClass('.slideOutRight')) {
        ulOpen = true;
    } else {
        ulOpen = false;
    }
});
3
On

Add ulOpen to your controller as a scope variable

Controller

$scope.ulOpen = false;

HTML

Then you should rely on the angularjs directive ng-click to set the value of ulOpen:

<button class="dropdown-toggle" type="button" ng-click="ulOpen=!ulOpen">Toggle Class</button>

And ng-class to switch class based on the value of ulOpen:

<ul class="dropdown-menu" ng-class="slideOutRight: ulOpen, slideInRight: !ulOpen">

In general, I would recommend whenever possible you find the pure angularjs solution. I find very few cases where there isn't a native angular directive that can handle what I would otherwise attempt to do in jquery.