Skip to content

Instantly share code, notes, and snippets.

@garbles
Last active August 29, 2015 14:08
Show Gist options
  • Save garbles/82c07bacf5b40c6f39c5 to your computer and use it in GitHub Desktop.
Save garbles/82c07bacf5b40c6f39c5 to your computer and use it in GitHub Desktop.
Example directive for creating elements wrapped in a `#shadow-root`
<shadow-root style="app/styles/isolated-styles.css">
<div some-directive></div>
</shadow-root>
angular.module('app')
.directive('shadowRoot', function ($document, $compile, $http, $q, $cacheFactory) {
var doc = $document[0],
cache = $cacheFactory('shadowRootDirective');
function fetchStyle (url) {
var cachedStyle = cache.get(url);
if (cachedStyle) {
return $q.when(cachedStyle);
}
return $http.get(url).then(function (response) {
var style = response.data;
cache.put(url, style);
return style;
});
}
return {
restrict: 'EA',
compile: function (element, attrs) {
var contents, root;
contents = element.children();
element.html('');
root = angular.element(
element[0].createShadowRoot();
);
root.append(contents);
if (attrs.hasOwnProperty('style')) {
fetchStyle(attrs.style).then(function (style) {
var tag = doc.createElement('style');
tag.textContent = style;
root.prepend(tag);
});
}
return {
pre: function (scope) {
$compile(root)(scope);
}
}
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment