在angularjs中使用不同页眉和页脚的最佳方法是什么?

jag*_*shs 3 javascript angularjs angularjs-directive angularjs-routing

我正在使用角度js单页应用程序.我有页眉和页脚的共同点,我的ng-view根据路由而变化.现在我需要一个具有不同页眉和页脚的页面.如何修改当前页面以包含它.

我的页面有ng-include ="shell.html",shell.html有ng-include ="topnavigation.html"和ng-view ="about.html"

我的ng-view指向基于路由的不同模板.例如:ng-view ="contact.html"

nul*_*ull 6

您可以通过维护页面上下文之类的内容轻松地完成此操作,其中包含其他模板的URL(在您的情况下为页脚和页眉).您需要做的就是将主页包装成如下所示:

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

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

</body>
Run Code Online (Sandbox Code Playgroud)

MainCtrl在这里做的唯一事情是暴露pageCtx$scope:

myApp.controller('MainCtrl', function($scope, myPageCtx) {
  $scope.pageCtx = myPageCtx;
});
Run Code Online (Sandbox Code Playgroud)

myPageCtx是一个完成所有"艰苦"工作的服务对象:

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

现在,与您的一个嵌入式ngView模板相关联的任何控制器都可以像MainCtrl修改任何上下文设置一样请求此服务:

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

你看到它在这个plunker行动.