What is the best way to have different headers and footers in angularjs?

三世轮回 提交于 2019-12-01 07:55:00

You can do that easily by maintaining something like a page context, which contains the urls to additional templates (in your case the footer and header). All you need to do is to wrap your main page to something like this:

<body ng-app="myApp" ng-controller="MainCtrl">

  <div ng-include="pageCtx.headerUrl"></div>  
  <div ng-view></div>
  <div ng-include="pageCtx.footerUrl"></div>

</body>

The only thing the MainCtrl is doing here is exposing the pageCtx on the $scope:

myApp.controller('MainCtrl', function($scope, myPageCtx) {
  $scope.pageCtx = myPageCtx;
});

The myPageCtx is a service object that does all the "hard" work:

myApp.provider('myPageCtx', function() {

  var defaultCtx = {
    title: 'Default Title',
    headerUrl: 'default-header.tmpl.html',
    footerUrl: 'default-footer.tmpl.html'
  };

  var currentCtx = angular.copy(defaultCtx);

  return {
    $get: function($rootScope) { 

      // We probably want to revert back to the default whenever
      // the location is changed.

      $rootScope.$on('$locationChangeStart', function() {
        angular.extend(currentCtx, defaultCtx);
      }); 

      return currentCtx; 
    }
  };
});

Now any controller associated with for instance one of your embedded ngView templates can request this service just like the MainCtrl and modify any of the context settings:

myApp.controller('MyViewCtrl', function($scope, myPageCtx) {
  myPageCtx.title = 'Title set from view 1';
  myPageCtx.footerUrl = 'view1-footer.tmpl.html';
});

You see it in action in this plunker.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!