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.
I have a page with ng-include="shell.html" and shell.html has ng-include="topnavigation.html" and ng-view="about.html"
and my ng-view points to different templates based on the routing. Ex: ng-view ="contact.html"
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.
来源:https://stackoverflow.com/questions/22248828/what-is-the-best-way-to-have-different-headers-and-footers-in-angularjs