我正在使用 angular js 单页应用程序。我有共同的页眉和页脚,我的 ng-view 根据路由变化。现在我需要一个包含不同页眉和页脚的页面。我如何修改当前页面以包含它。
我有一个包含 ng-include="shell.html"的页面 和 shell.html 有 ng-include="topnavigation.html"和 ng-view="about.html"
我的 ng-view 根据路由指向不同的模板。 例如:ng-view ="contact.html"
最佳答案
您可以通过维护页面上下文之类的内容轻松地做到这一点,其中包含其他模板的 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 在这里做的唯一一件事是在 $scope
上公开 pageCtx
:
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 模板之一关联的任何 Controller 都可以像 MainCtrl
一样请求此服务并修改任何上下文设置:
myApp.controller('MyViewCtrl', function($scope, myPageCtx) {
myPageCtx.title = 'Title set from view 1';
myPageCtx.footerUrl = 'view1-footer.tmpl.html';
});
您可以在 this plunker 中看到它的实际应用.
关于javascript - 在 angularjs 中有不同的页眉和页脚的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22248828/