Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs: Hide navbar element based on route?

I'm trying to figure out how to show or hide an element in my navbar based on the route, or the current view being displayed. For example, I have an basic/advanced toggle button that I put in the navbar (Bootstrap 3) when the user is on the search form. But when they are anywhere else in the app that toggle button should be hidden.

In terms of the DOM, it's just a list item that builds out the nav. I'm not sure if I should show or hide based on a global value that gets set on each view, or if I can just use the route or view name. If so how that would work?

Thanks!

like image 529
Eddie Avatar asked May 23 '14 20:05

Eddie


2 Answers

One solution is to build a function in the controller that is responsible for the navbar that could be queried to determine if the element should be displayed:

$scope.isActive = function(viewLocation) {
    return viewLocation === $location.path();
};

(The above code uses Angular's $location service)

Then within the template, you can show/hide based on the result of the call (passing in the route that should toggle displaying the element):

ng-show="isActive('/search-form')"
like image 95
dylants Avatar answered Oct 22 '22 01:10

dylants


Here's the approach I took with ui-router:

I only want to hide the navbar for a small number of pages so I went with an opt out property on the state(s) that I want to hide the navbar.

.state('photos.show', {
  url: '/{photoId}',
  views: {
    "@" : {
      templateUrl: 'app/photos/show/index.html',
      controller: 'PhotoController'
    }
  },
  hideNavbar: true
})

Inject $state in your navbar's controller and expose it to the template:

$scope.state = $state;

Then add ng-hide to your navbar template:

<nav ng-hide="state.$current.hideNavbar" ...
like image 33
Andy Gaskell Avatar answered Oct 22 '22 00:10

Andy Gaskell