Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close dropdown menu on click in angular bootstrap ui

I have dropdown menu on navigation bar shown only for mobile devices. When dropdown menu link is clicked, it just move to another path. As you know, this action will not refresh entire page. But even after i click menu under dropdown, it does not go away.

I want to close the dropdown if the menu link is clicked or when route is changed. How do i do it in angularjs bootstrap?

like image 881
Fizer Khan Avatar asked Oct 21 '22 17:10

Fizer Khan


1 Answers

If you are updating the route on clicking any option of the bootstrap dropdown menu then you can just watch for route change event:

Suppose you have below link which opens up a tooltip.

<a class="dropdown-toggle">
  Click me for a dropdown, yo!
</a>

<ul class="dropdown-menu">
  <li ng-repeat="choice in items" class="ng-scope">
    <a class="ng-binding">The first choice!</a>
  </li><li ng-repeat="choice in items" class="ng-scope">
    <a class="ng-binding">And another choice for you.</a>
  </li><li ng-repeat="choice in items" class="ng-scope">
    <a class="ng-binding">but wait! A third!</a>
  </li>
</ul>

$scope.$on('$routeUpdate', function(scope, next, current) {
   $('html').trigger('click');
});

The above will work but there is absolutely no need to grab html element on every route change (as it causes reflow) so better to put it in directive as follows:

<html hide-dropdown>

angular.module('App', []).
  directive('hideDropdown', function() {
    return {
       restrict: 'A',
       link: function(scope, element) {
         scope.$on('$routeUpdate', function(scope, next, current) {
           element.trigger('click');
         });
       } 
    }
  });
like image 74
codef0rmer Avatar answered Oct 27 '22 07:10

codef0rmer