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

问题描述:

我正在使用angular js单页应用程序.我有相同的页眉和页脚,并且ng-view会根据路由进行更改.现在,我需要一个具有不同页眉和页脚的页面.我如何修改当前页面以包含它.

I am using angular js single page app. I have header and footer in common and my ng-view changes according to the routing. Now I need to have a page with different header and footer. How can i modify the current page to include it.

我有一个页面,其中包含ng-include ="shell.html" 并且shell.html具有ng-include ="topnavigation.html"和ng-view ="about.html"

I have a page with ng-include="shell.html" and shell.html has ng-include="topnavigation.html" and ng-view="about.html"

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

and my ng-view points to different templates based on the routing. Ex: ng-view ="contact.html"

您可以通过维护诸如页面上下文之类的内容轻松地做到这一点,该页面上下文包含其他模板的URL(在您的情况下为页脚和页眉).您需要做的就是将您的主页包装成这样:

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>

MainCtrl在这里所做的唯一一件事就是将pageCtx暴露在$scope上:

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

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

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; 
    }
  };
});

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

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.