有条件地在 Angular 应用程序中包含侧边栏和 header

Conditionally include sidebar and header in Angular App

在某些视图上我想要侧边栏和 header,而有些则不需要。使用 AngularJS,实现此目标的最佳方法是什么。

我目前想到的解决方案是在侧边栏上使用 ng-if 和 header DIV,在我的控制器中,设置一个 $scope 变量以设置为 true 或 false根据视图,我希望边栏和 header 出现。

一个具体的例子是Youtube.com。在 Youtube 的主页上,请注意有一个侧边栏和一个带有过滤器的 sub-header:"What to Watch" 和 "Music"。但是,在任何视频页面上,边栏和 sub-header 都不存在。我想在 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;
    }]);

我不会在 controller 级别进行配置,而是在 route 级别进行配置。并将监听 $routeChangeSuccess 事件并更新 $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;
    });
}]);

在您的模板中,您可以只使用 ng-if="showHeader"。我觉得它很容易维护。

ng-if="showHeader == true" 像这样使用

 <ng-include ng-if="showHeader == true" src="'./partials/mainSubHeader.html'"></ng-include>