Search code examples
jqueryangularjsslidedownng-animate

dynamic slideToggle with AngularJS


I'm pretty new to AngularJS and I'm trying to migrate the following piece of jQuery code to AngularJS.

$('#someid').on('click', 'someclass', function() {
  $(this).next().slideToggle('fast');
});

My HTML that I began converting to AngularJS looks something like

<ul id='someid'>
  <li ng-repeat="...">
    <ul>
      <li class="someclass">{{ ... }}</li>
      <li style="display:none">the part that will be slideToggle'd</li> 
    </ul>
  </li>
</ul>

Elements are added to the ng-repeat list dynamically when the user interacts with the app, hence the jQuery.on(). I'm OK using an unstable version of AngularJS if it helps.

How should I rewrite the jQuery fragment in AngularJS? I've tried a few things now including adding a new directive, playing with ng-animate, etc. But when I added jQuery code into my ng controller, that started to look ugly -- I'd like to avoid anything hybrid.

Thanks a lot!


Solution

  • One way to do that would be by writing a directive but ideally you should use ng-animate along with ng-show:

    Firstly, toggle a property inside ng-click that you would keep on the "li" with the class "someclass":

    <li class="someclass" ng-click="item.isVisible = !item.isVisible;">{{item.name}}</li>
    

    and then use ng-show along with ng-animate on the part that would be slideToggle'd.

    <li ng-show="item.show" ng-animate="'animate'" style="display:none">the part that will be slideToggle'd</li>
    

    You would also need to write the animation css class for ng-animate to work.

    Hope this helps.