我知道这个问题现在很老了,但是在对这个问题的各种解决方案做了大量的研究之后,我想我可能已经想出了一个更好的解决方案.
UPDATE 1:自从发布这个答案以来,我已经将所有这些代码添加到我发布到GitHub的一个简单服务中.回购位于here.请随时查看以了解更多信息.
UPDATE 2:如果您所需要的只是为您的路由引入样式表的轻量级解决方案,那么这个答案是很棒的.如果您想要一个更完整的解决方案来管理整个应用程序中的按需样式表,您可能需要签出Door3's AngularCSS project.它提供了更细粒度的功能.
如果将来有人对此感兴趣,这里是我想出来的:
1. Create a custom directive for the 100 element:
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;
});
}
});
}
};
}
]);
此指令执行以下操作:
- It compiles (using
$compile
) an html string that creates a set of <link />
tags for every item in the scope.routeStyles
object using ng-repeat
and ng-href
.
- 它将编译后的
<link />
个元素集附加到<head>
标记.
- 然后,它使用
$rootScope
来监听'$routeChangeStart'
个事件.对于每个'$routeChangeStart'
事件,它获取"当前"$$route
对象(用户将要离开的路由),并从<head>
标记中删除其部分特定的CSS文件.它还获取"Next"$$route
对象(用户将要前往的路由),并将其任何特定于部分的CSS文件添加到<head>
标记.
- 编译后的
<link />
标记的ng-repeat
部分根据向scope.routeStyles
对象添加的内容或从scope.routeStyles
对象中删除的内容来处理特定于页面的样式表的所有添加和删除.
Note: this requires that your 100 attribute is on the 101 element, not on 102 or anything inside of 101.
2. Specify which stylesheets belong to which routes using the 100:
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
属性.该对象作为.$$route
传递给每个'$routeChangeStart'
事件.因此,在收听'$routeChangeStart'
事件时,我们可以获取我们指定的css
属性,并根据需要附加/删除这<link />
个标记.请注意,在路由上指定css
属性是完全可选的,因为在'/some/route/2'
示例中省略了它.如果路由没有css
属性,<head>
指令将对该路由不做任何操作.还要注意,每个路由甚至可以有多个特定于页面的样式表,如上面的'/some/route/3'
示例所示,其中css
属性是指向该路由所需样式表的相对路径array.
3. You're done个
这两件事设置了所有需要的东西,在我看来,它用尽可能干净的代码完成了这项工作.
希望这能帮助其他可能和我一样在这个问题上苦苦挣扎的人.