Angular UI Bootstrap - 响应式导航栏 - 在 state/view 变化时隐藏

Angular UI Bootstrap - Responsive Navbar - Hide on state/view change

我在我的应用程序中使用 Angular UI Bootstrap#0.12.1 和 UI router#0.2.15。

我有一个响应式导航栏,工作正常。问题出在移动视图中 当我单击任何 menu/link 时,state/view 会发生变化。但导航栏似乎留在那里。

我想让它隐藏起来。如果它作为下拉菜单出现,那就太好了。

I created a Plunkr Sample

以下是我的导航栏

<nav class="navbar navbar-default" role="navigation" ng-controller="MenuCtrl">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">

      <button id="btn-menu-toggle" type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Brand</a>
    </div>
    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" ng-class="!navCollapsed && 'in'">

      <ul class="nav navbar-nav">
        <li ng-class="{'active':$state.includes('home')}" ng-click="collapseMenu()"><a ui-sref="home.main1">Home</a></li>
        <li ui-sref-active="active" ng-click="collapseMenu()"><a ui-sref="dashboard.dash1">Dashboard</a></li>
        <li ui-sref-active="active" ng-click="collapseMenu()"><a ui-sref="report">Reports</a></li>
      </ul>
    </div>
    <!-- /.navbar-collapse -->
  </nav>

我尝试在任何菜单点击时调用 collapseMenu() 函数,我在控制器中有以下代码

$scope.collapseMenu = function() {
        if ($(window).width() <= 768) {
            console.log('hiding');
            $('#btn-menu-toggle').click();
        }
    }

但是我遇到了错误

Error: [$rootScope:inprog] $apply already in progress
http://errors.angularjs.org/1.4.2/$rootScope/inprog?p0=%24apply
    at REGEX_STRING_REGEXP (angular.js:68)
    at beginPhase (angular.js:16202)
    at Scope.parent.$get.Scope.$apply (angular.js:15946)
    at HTMLButtonElement.<anonymous> (angular.js:23305)
    at HTMLButtonElement.eventHandler (angular.js:3273)
    at Object.n.event.trigger (jquery-2.1.4.min.js:3)
    at HTMLButtonElement.<anonymous> (jquery-2.1.4.min.js:3)
    at Function.n.extend.each (jquery-2.1.4.min.js:2)
    at n.fn.n.each (jquery-2.1.4.min.js:2)
    at n.fn.extend.trigger (jquery-2.1.4.min.js:3)

如何解决?有没有更好的方法使导航栏在移动视图中成为下拉菜单?

谢谢。

您不需要显式调用 .click()。只需更改控制菜单状态的变量:

$scope.collapseMenu = function() {
    if ($(window).width() <= 768) {
        console.log('hiding');
        $scope.navCollapsed = true;
    }
} 

Working fork on plunkr