3 css conditional angularjs route-provider
我想仅在用户访问contact.html我的AngularJS应用程序/站点上的视图时才加载特定的CSS文件.我找到了这个对我来说几乎有意义的答案如何在AngularJS中包含视图/部分特定样式 charlietfl接受的答案如下:
可以附加一个新的样式表
$routeProvider.为简单起见,我使用字符串但也可以创建新的链接元素,或者为样式表创建服务Run Code Online (Sandbox Code Playgroud)/* check if already exists first - note ID used on link element*/ /* could also track within scope object*/ if( !angular.element('link#myViewName').length){ angular.element('head').append('<link id="myViewName" href="myViewName.css" rel="stylesheet">'); }在页面中预先编码的最大好处是任何背景图像都已经存在,而且更少的谎言
FOUC
问题是我不知道在我$routeProvider添加代码的确切位置.charlietfl提到将其放在评论中的位置
不是如果没有调用路线的时间.可以将此代码放在routeProvider中的控制器回调中,或者可能在解析回调中,这可能会更快触发
我修改了我$routeProvider的建议.我resolve在下面的对象中添加了一个.when('/contact'.这是我的代码
angular.module('maxmythicApp', ['ngResponsiveImages'])
.config(function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix = '!';
$routeProvider
.when('/', {
templateUrl: '/views/design.html',
controller: 'MainCtrl'
})
.when('/design', {
templateUrl: '/views/design.html',
controller: 'MainCtrl'
})
.when('/about', {
templateUrl: '/views/about.html',
controller: 'MainCtrl'
})
.when('/contact', {
templateUrl: '/views/contact.html',
controller: 'MainCtrl',
resolve:
if( !angular.element('link#myViewName').length){
angular.element('head').append('<link id="myViewName" href="myViewName.css" rel="stylesheet">');
}
})
.otherwise({
redirectTo: '/'
});
});
Run Code Online (Sandbox Code Playgroud)
这会有用吗?
我为它做了一个服务.
代码的重要部分:
var head = angular.element(document.querySelector('head')); // TO make the code IE < 8 compatible, include jQuery in your page and replace "angular.element(document.querySelector('head'))" by "angular.element('head')"
if(head.scope().injectedStylesheets === undefined)
{
head.scope().injectedStylesheets = [];
head.append($compile("<link data-ng-repeat='stylesheet in injectedStylesheets' data-ng-href='{{stylesheet.href}}' rel='stylesheet' />")(scope)); // Found here : http://stackoverflow.com/a/11913182/1662766
}
head.scope().injectedStylesheets.push({href: "/url/to/style.css"});
Run Code Online (Sandbox Code Playgroud)
Github中的完整代码:https://github.com/Yappli/angular-css-injector)