Collapse navbar on navigate (link click) in mobile mode
angularjs, twitter-bootstrap
Solution
Here's the angular directive I ended up using. There's a couple of things to watch out for.
- Don't collapse the menu when in desktop mode (look for overflow-y == auto)
- Handle menu state when resizing window with an open menu that closes when the window grows.
I use the ic-nav-autoclose directive on the element with the nav class.
angular.module('incmn')
.directive('icNavAutoclose', function () {
console.log("icNavAutoclose");
return function (scope, elm, attrs) {
var collapsible = $(elm).find(".navbar-collapse");
var visible = false;
collapsible.on("show.bs.collapse", function () {
visible = true;
});
collapsible.on("hide.bs.collapse", function () {
visible = false;
});
$(elm).find("a").each(function (index, element) {
$(element).click(function (e) {
if (visible && "auto" == collapsible.css("overflow-y")) {
collapsible.collapse("hide");
}
});
});
}
});
Problem
I'm using bootstrap 3 with angular. When I click a link the page isn't reloaded, causing the menu to stay open when in mobile mode. How do I make the menu close automatically when I click a menu item? I have tried just adding `data-toggle="collapse" data-target=".navbar-responsive-collapse"` to the `a` tags, but it causes strange behavior in desktop mode.