有条件地包括Angular App中的侧边栏和标题

Ras*_*had 2 angularjs angularjs-ng-include angular-ng-if

在某些视图中,我想要一个侧边栏和标题,有些我不想.使用AngularJS,实现这一目标的最佳方法是什么.

我当前的解决方案是在侧边栏和标题DIV上使用ng-if,并在我的控制器中,将$ scope变量设置为true或false,具体取决于我希望侧边栏和标题显示的视图.

一个具体的例子是Youtube.com.在Youtube的主页上,请注意有一个侧边栏和一个带有过滤器的子标题:"要注意什么"和"音乐".但是,在任何视频页面上,侧边栏和子标题都不存在.我想在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>
Run Code Online (Sandbox Code Playgroud)

discussionBoard.html

    <div class="discussionBoard" ng-controller="DiscussionBoardController">
         <h2>DiscussionBoard</h2>
    </div>
Run Code Online (Sandbox Code Playgroud)

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;
    }]);
Run Code Online (Sandbox Code Playgroud)

moh*_*ias 7

而不是在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;
    });
}]);
Run Code Online (Sandbox Code Playgroud)

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