@tennisgent 的解决方案很棒。不过,我觉得有点局限。
Angular 中的模块化和封装超越了路由。基于 Web 正在朝着基于组件的开发方式发展,在指令中应用这一点也很重要。
如您所知,在 Angular 中,我们可以在页面和组件中包含模板(结构)和控制器(行为)。 AngularCSS 启用了最后一个缺失的部分:附加样式表(演示文稿)。
对于完整的解决方案,我建议使用 AngularCSS。
- 支持 Angular 的 ngRoute、UI 路由器、指令、控制器和服务。
- 不需要在
<html> 标记中包含ng-app。当您在同一页面上运行多个应用时,这一点很重要
- 您可以自定义样式表的注入位置:头部、正文、自定义选择器等...
- 支持预加载、持久化和缓存清除
- 支持媒体查询并通过 matchMedia API 优化页面加载
https://github.com/door3/angular-css
这里有一些例子:
路线
$routeProvider
.when('/page1', {
templateUrl: 'page1/page1.html',
controller: 'page1Ctrl',
/* Now you can bind css to routes */
css: 'page1/page1.css'
})
.when('/page2', {
templateUrl: 'page2/page2.html',
controller: 'page2Ctrl',
/* You can also enable features like bust cache, persist and preload */
css: {
href: 'page2/page2.css',
bustCache: true
}
})
.when('/page3', {
templateUrl: 'page3/page3.html',
controller: 'page3Ctrl',
/* This is how you can include multiple stylesheets */
css: ['page3/page3.css','page3/page3-2.css']
})
.when('/page4', {
templateUrl: 'page4/page4.html',
controller: 'page4Ctrl',
css: [
{
href: 'page4/page4.css',
persist: true
}, {
href: 'page4/page4.mobile.css',
/* Media Query support via window.matchMedia API
* This will only add the stylesheet if the breakpoint matches */
media: 'screen and (max-width : 768px)'
}, {
href: 'page4/page4.print.css',
media: 'print'
}
]
});
指令
myApp.directive('myDirective', function () {
return {
restrict: 'E',
templateUrl: 'my-directive/my-directive.html',
css: 'my-directive/my-directive.css'
}
});
此外,您可以将$css 服务用于边缘情况:
myApp.controller('pageCtrl', function ($scope, $css) {
// Binds stylesheet(s) to scope create/destroy events (recommended over add/remove)
$css.bind({
href: 'my-page/my-page.css'
}, $scope);
// Simply add stylesheet(s)
$css.add('my-page/my-page.css');
// Simply remove stylesheet(s)
$css.remove(['my-page/my-page.css','my-page/my-page2.css']);
// Remove all stylesheets
$css.removeAll();
});
您可以在此处阅读有关 AngularCSS 的更多信息:
http://door3.com/insights/introducing-angularcss-css-demand-angularjs