Search code examples
angularjsangularjs-ng-includeangular-ng-if

Conditionally include sidebar and header in Angular App


On certain views I want a sidebar and header, and some I do not. Using AngularJS, what is the best approach to achieve this.

My current solution in mind is to use ng-if on the sidebar and header DIV, and in my Controllers, set a $scope variable to be set to true or false depending on the views I want the sidebar and header to appear.

A concrete example would be Youtube.com. On Youtube's homepage, notice there is a sidebar and a sub-header with the filters: "What to Watch" and "Music" in it. However, on any video page, the sidebar and sub-header doesn't exist. I want to achieve that in AngularJS.

index.html

    <html ng-app="demoApp">

    <body ng-controller="demoAppMainController">

        <header>
            <ng-include src="'./partials/mainHeader.html'"></ng-include>
            <ng-include ng-if="showSubHeader" src="'./partials/mainSubHeader.html'"></ng-include>
        </header>

        <main>
            <ng-view></ng-view>
        </main>


    </body>
    </html>

discussionBoard.html

    <div class="discussionBoard" ng-controller="DiscussionBoardController">
         <h2>DiscussionBoard</h2>
    </div>

controllers.js

    var demoAppControllers = angular.module('demoAppControllers', []);

    demoAppControllers.controller('demoAppMainController', ['$scope', function($scope) {
            $scope.showSubHeader = true;
    }]);

    opinionLensControllers.controller('DiscussionBoardController', ['$scope', function($scope) {
            $scope.showSubHeader = false;
    }]);

Solution

  • Instead of doing it in controller level, I would configure that in route level. And will listen to the $routeChangeSuccess event and update the $rootScope.

    demoAppControllers.config(function ($routeProvider) {
        $routeProvider.
        when('/home', {
            templateUrl: 'home.html',
            controller: 'HomeController',
            showHeader : true
        }).
        when('/about', {
            templateUrl: 'discuss.html',
            controller: 'DiscussionBoardController',
            showHeader : false
        }).
        otherwise({
            redirectTo: '/home'
        });
    }).
    run(['$rootScope', function($rootScope) {
        $rootScope.$on("$routeChangeSuccess", function(event, next, current) {
            $rootScope.showHeader = next.$$route.showHeader;
        });
    }]);
    

    In your templates, you can just use ng-if="showHeader". It will be easily maintainable I feel.