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

时间:2016-03-11 02:38:13

标签: javascript jquery angularjs

我在angularjs应用程序中遇到了一个奇怪的情况。我的观点如下

的index.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进行前端验证。

1 个答案:

答案 0 :(得分:0)

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

这是一个有效的例子。

&#13;
&#13;
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;
  }
});
&#13;
nav {
  width: 100%;
  height: 50px;
  display: block;
  background-color: grey;
  color: black;
}
&#13;
<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>
&#13;
&#13;
&#13;