Search code examples
javascriptangularjscss-animationsng-animate

Javascript toggle animation of height in Angular


I have the following animation defined in my Angular app for toggling the hight/opacity of an element.

It works as expected, however I'm now using it to toggle a 'main menu' and the 'sub-menus' within.

When the main menu is opened it increases from 0 to X height, then if I open a sub menu the main menu remains at X height, whereas I'd like it to expand to the height of the main menu + height of the newly opened sub-menu.

app.animation('.slide_toggle', ['$animateCss',
  function ($animateCss) {
    return {
      addClass: function (element, className, done) {
        if (className == 'ng-hide') {
          var animator = $animateCss(element, {
            to: { height: '0px', opacity: 0 }
          });
          if (animator) {
            return animator.start().done(function () {
              element[0].style.height = '';
              done();
            });
          }
        }
        done();
      },
      removeClass: function (element, className, done) {
        if (className == 'ng-hide') {
          var height = element[0].offsetHeight;
          var animator = $animateCss(element, {
            from: { height: '0px', opacity: 0 },
            to: { height: height + 'px', opacity: 1 }
          });
          if (animator) {
            return animator.start().done(done);
          }
        }
        done();
      }
    };
  }
]);

I'm open to using a different animation method to the one above as long as the animation opens and closes smoothly.


Solution

  • There were problems with all the 'Angular only' slide toggle methods I could find (mainly due to child element heights not being dealt with properly). In the end I included jQuery in the project and used the comprehensive slideUp and slideDown functionality from there like so:

    myApp.animation('.slide', function () {
       return {
          beforeAddClass: function (element, className, done) {
             if (className === 'ng-hide') {
                element.slideUp({ duration: 350 }, done);
             }
          },
          removeClass: function (element, className, done) {
             if (className === 'ng-hide') {
                element.hide().slideDown({ duration: 350 }, done);
             }
          }
       }
    });