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

时间:2014-03-07 11:26:27

标签: javascript angularjs angularjs-directive angularjs-routing

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

我有一个ng-include =“shell.html”的页面 和shell.html有ng-include =“topnavigation.html”和ng-view =“about.html”

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

1 个答案:

答案 0 :(得分: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>

MainCtrl在这里唯一做的就是在pageCtx上公开$scope

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

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

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

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

您在this plunker中看到了它。

相关问题