How do I use angular ng-hide based on the page/route that I am currently on?

silvster27 picture silvster27 · Mar 12, 2014 · Viewed 37.6k times · Source

have an angular application that I want to hide one of the 'included views' if the main view is the homepage view.

<div id="page" ng-class="{ showNav: $root.showNav }">
    <header id="pageHeader" ng-controller="HeaderCtrl" data-ng-include="'views/includes/header.html'"></header>
    <div id="pageHero" ng-show='$rootScope.fullView' ng-controller="MainsearchCtrl" data-ng-include="'views/mainSearch.html'"></div>
    <div id="pageContent" ng-view=""></div>
</div>

Answer

Vadim picture Vadim · Mar 12, 2014

You can inject either $route or $location into your controller, fetch needed value from one of these services and use it in ng-show or ng-if.

Example of using $route and $location you can see here.

Here is one of possible ways of doing it:

JavaScript

angular.module('app', ['ngRoute']).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.
      when('/one', {
        controller: 'routeController',
        templateUrl: 'routeTemplate.html'
      }).
      when('/two', {
        controller: 'routeController',
        templateUrl: 'routeTemplate.html'
      }).
      otherwise({
        redirectTo: '/one'
      })
  }]).
  controller('routeController', ['$scope', '$location', function($scope, $location) {
    $scope.showPageHero = $location.path() === '/one';
  }]);

routeTemplate.html

<div>
  <h1>Route Template</h1>
  <div ng-include="'hero.html'" ng-if="showPageHero"></div>
  <div ng-include="'content.html'"></div>
</div>

Plunker: http://plnkr.co/edit/sZlZaz3LQILJcCywB1EB?p=preview