Last active
August 29, 2015 14:08
-
-
Save garbles/82c07bacf5b40c6f39c5 to your computer and use it in GitHub Desktop.
Example directive for creating elements wrapped in a `#shadow-root`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<shadow-root style="app/styles/isolated-styles.css"> | |
<div some-directive></div> | |
</shadow-root> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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