AngularJS with UI Bootstrap - Automatically collapse menu when nav item is clicked

971 Views Asked by At

In this example: https://plnkr.co/edit/O9fbLcTV7QPvqB3FpiAA?p=preview

When you click the hamburger menu icon and select a nav item, it leaves the menu open until you click the hamburger icon again. Is there a good way to automatically collapse when a menu item is selected?

I tried:

<li><a href="#" ng-click="isNavCollapsed = !isNavCollapsed;">Link 1</a></li>

Which works, but will trigger the nav menu collapse animation when not in mobile mode (on a wider screen).

2

There are 2 best solutions below

2
Pop-A-Stash On

You can add an event listener using plain JS, where you can check that the width of the window matches your mobile breakpoint. Just make sure you wrap the actual change to the scope variable in a $apply function otherwise AngularJS will not know about it:

https://plnkr.co/edit/ZzbXZ3lFxqX6Tlra46W5?p=preview

angular.module('ui.bootstrap.demo').controller('CollapseDemoCtrl', function ($scope) {
  $scope.isNavCollapsed = true;
  $scope.isCollapsed = false;
  $scope.isCollapsedHorizontal = false;


  document.addEventListener('click', collapseMenu, false);

  function collapseMenu(event) {
    if(event.target.matches('.nav.navbar-nav li a')  && window.innerWidth < 768) {
      $scope.$apply(function() {
        $scope.isNavCollapsed = true;
      });
    }
  }

  // prevent memory leaks by removing listener when scope is destroyed
  $scope.$on("$destroy", function() {
    document.removeEventListener('click', collapseMenu, false);
  });

});

Note that this will require you to keep your CSS and JS in sync with regards to the breakpoint value

3
Ted Scheckler On

I solved it by adding a flag 'hamburger_open' that triggers true on expanding() and false on collapsing().

<div class="collapse navbar-collapse" uib-collapse="isNavCollapsed" expanding="hamburger_open=true" collapsing="hamburger_open=false">

... and hamburger_collapse function that checks if hamburger_open is true:

<li><a href="#" ng-click="hamburger_collapse()">Link 1</a></li>

  ...
  $scope.hamburger_collapse = function() {
    if($scope.hamburger_open) {
      $scope.isNavCollapsed = !$scope.isNavCollapsed;
    }
  }
  ...

https://plnkr.co/edit/IFIL8lgjK0oGDqZkLK5F?p=preview

Seems like an odd thing to have to do considering every modern mobile menu automatically collapses when a menu item is chosen.