This repository has been archived by the owner on Jul 21, 2023. It is now read-only.
forked from GabrielDelepine/angular-css-injector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
angular-css-injector.js
78 lines (68 loc) · 3.04 KB
/
angular-css-injector.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
* angular-css-injector v1.0.1
* Written by Gabriel Delépine
* License: MIT
* https://github.com/Yappli/angular-css-injector/
*/
angular.module('angular.css.injector', [])
.service('cssInjector', [
'$compile',
'$rootScope',
function($compile, $rootScope)
{
// Variables
var singlePageMode = false,
head = angular.element(typeof jQuery == "undefined" ? document.querySelector('head') : 'head'), // TO make the code IE < 8 compatible, include jQuery in your page
scope;
// Capture the event `locationChangeStart` when the url change. If singlePageMode===TRUE, call the function `removeAll`
$rootScope.$on('$locationChangeStart', function()
{
if(singlePageMode === true)
removeAll();
});
// Always called by the functions `addStylesheet` and `removeAll` to initialize the variable `scope`
var _initScope = function()
{
if(scope === undefined)
scope = head.scope(); // We initialise head's scope in a separated function because it is not defined at the time of the initialisation of the service.
};
// Used to add a CSS files in the head tag of the page
var addStylesheet = function(href)
{
_initScope();
if(scope.injectedStylesheets === undefined)
{
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
}
else
{
for(var i in scope.injectedStylesheets)
{
if(scope.injectedStylesheets[i].href == href) // An url can't be added more than once. I use a loop FOR, not the function indexOf to make the code IE < 9 compatible
return;
}
}
scope.injectedStylesheets.push({href: href});
};
// Used to remove all of the CSS files added with the function `addStylesheet`
var removeAll = function()
{
_initScope();
if(scope.injectedStylesheets !== undefined)
scope.injectedStylesheets = []; // Make it empty
};
// Used to set the boolean `singlePageMode`. If singlePageMode===TRUE, the function `removeAll` will be call every time the page change (based on the angular event `$locationChangeStart`)
var setSinglePageMode = function(bool)
{
if(bool !== true && bool !== false)
throw("Angular service `cssInjector` : function `setSinglePageMode` : Error parameter, boolean required.");
singlePageMode = bool;
};
return {
add: addStylesheet,
removeAll: removeAll,
setSinglePageMode: setSinglePageMode,
};
}
]);