Angularjs:隐藏包含动态参数的网址的导航栏

Angularjs: Hide navbar for urls containing dynamic parameters

本文关键字:导航 参数 隐藏 包含 动态 Angularjs      更新时间:2023-09-26

我的angularjs应用程序中遇到了一个奇怪的情况。我有一个像下面这样的视图

索引.html

<body>
<nav ng-include="'/views/partials/nav_bar.html'" ng-if='location.path() !== "/" && location.path() !==  "/signin" && location.path() !== "/register" && location.path() !==  "/forgot_password" && location.path() !== "/update_password"  && location.path() !== "{{page_id}}"  '></nav>
 <div data-ng-view>
 </div>
</body>

你可以看到它不包含任何控制器初始化(因为所有其他具有控制器规范的页面都将呈现在data-ng-view中)。但是我想隐藏特定页面的导航栏。我在上面的标签上使用ng-include(非常丑陋的条件 - 我接受)。但是我有一个带有动态参数的页面,说'search/:id'现在location.path()无法工作.我的问题是我想隐藏一些静态#动态网址的导航栏。

我正在使用ng-token-auth进行前端验证。

我会将条件移动到控制器中,然后您可以更简洁地确定导航是否应该可见。

这是一个工作示例。

angular.module('app', []).controller('BaseController', function($scope, $location) {
  var excludeUrls = ["/signin", "/register", "/forgot_password", "/update_password"];
  $scope.path = '/someUrl';
  $scope.navbarIsVisible = function() {
    var path = $scope.path; //this would be $location.path() normally, but for this example we are allowing it to be manually entered
    if (path === '/') {
      return false;
    }
    //anytime the url contains any variation of the exclude urls, hide the navbar
    for (var i = 0; i < excludeUrls.length; i++) {
      var excludeUrl = excludeUrls[i];
      //if the path starts with the given url, hide the navbar
      if (path.indexOf(excludeUrl) === 0) {
        return false;
      }
    }
    return true;
  }
});
nav {
  width: 100%;
  height: 50px;
  display: block;
  background-color: grey;
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="BaseController">
  <nav ng-if='navbarIsVisible()'>I am the navbar and I am visible</nav>
  Enter the url to see if the navbar should be visible:
  <input type="text" ng-model="path" />
</div>
</div>