我知道这个问题现在已经很老了,但是在对这个问题的各种解决方案进行了大量研究之后,我认为我可能已经提出了一个更好的解决方案。
自发布此答案以来,我已将所有这些代码添加到我发布到GitHub的简单服务中。
如果您需要的只是为路线引入样式表的轻量级解决方案,那么此答案就很好。如果您想要一个更完整的解决方案来管理整个应用程序中的按需样式表,则可能需要检出Door3的AngularCSS项目。它提供了更多细粒度的功能。
如果将来有人感兴趣,这是我想出的:
app.directive('head', ['$rootScope','$compile',
function($rootScope, $compile){
return {
restrict: 'E',
link: function(scope, elem){
var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" />';
elem.append($compile(html)(scope));
scope.routeStyles = {};
$rootScope.$on('$routeChangeStart', function (e, next, current) {
if(current && current.$$route && current.$$route.css){
if(!angular.isArray(current.$$route.css)){
current.$$route.css = [current.$$route.css];
}
angular.forEach(current.$$route.css, function(sheet){
delete scope.routeStyles[sheet];
});
}
if(next && next.$$route && next.$$route.css){
if(!angular.isArray(next.$$route.css)){
next.$$route.css = [next.$$route.css];
}
angular.forEach(next.$$route.css, function(sheet){
scope.routeStyles[sheet] = sheet;
});
}
});
}
};
}
]);
该指令执行以下操作:
这要求您的ng-app
属性位于<html>
元素上,而不位于上<body>
或内<html>
。
app.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/some/route/1', {
templateUrl: 'partials/partial1.html',
controller: 'Partial1Ctrl',
css: 'css/partial1.css'
})
.when('/some/route/2', {
templateUrl: 'partials/partial2.html',
controller: 'Partial2Ctrl'
})
.when('/some/route/3', {
templateUrl: 'partials/partial3.html',
controller: 'Partial3Ctrl',
css: ['css/partial3_1.css','css/partial3_2.css']
})
}]);
此配置将自定义css
属性添加到用于设置每个页面路由的对象。该对象'$routeChangeStart'
作为传递给每个事件.$$route
。因此,在侦听'$routeChangeStart'
事件时,我们可以获取css
我们指定的属性,并<link />
根据需要添加/删除这些标签。请注意,css
在路由上指定属性是完全可选的,因为'/some/route/2'
示例中已将其省略。如果路由没有css
属性,则该<head>
指令将对该路由完全不执行任何操作。还要注意,每个路由甚至可以有多个页面特定的样式表,如上'/some/route/3'
例所示,其中的css
属性是该路由所需样式表的相对路径的数组。
我认为,这两件事设置了所需的一切,并且使用了最干净的代码来完成了它。
希望这对我可能一直在努力解决此问题的其他人有所帮助。