在 angularjs 中拥有不同页眉和页脚的最佳方法是什么? [英] What is the best way to have different headers and footers in angularjs?

查看:30
本文介绍了在 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 在这里做的唯一一件事就是在 $scope 上暴露 pageCtx:

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

您可以在 这个 plunker 中看到它的作用.

You see it in action in this plunker.

这篇关于在 angularjs 中拥有不同页眉和页脚的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆