Last active
May 1, 2019 00:51
-
-
Save tleunen/5277011 to your computer and use it in GitHub Desktop.
Here is a directive in AngularJS to embed a Gist. This technique uses an iframe to add the gist because AngularJS doesn't handle script tags inside a template. And even if it does (with jQuery), it won't work as expected because Gist uses document.write. The iframe solves both issues.
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
<!-- In your template --> | |
<div data-gist="{{gistId}}"></div> |
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('T.directives', []). | |
directive('gist', function() { | |
return function(scope, elm, attrs) { | |
var gistId = scope.gistId; | |
var iframe = document.createElement('iframe'); | |
iframe.setAttribute('width', '100%'); | |
iframe.setAttribute('frameborder', '0'); | |
iframe.id = "gist-" + gistId; | |
elm[0].appendChild(iframe); | |
var iframeHtml = '<html><head><base target="_parent"><style>table{font-size:12px;}</style></head><body onload="parent.document.getElementById(\'' + iframe.id + '\').style.height=document.body.scrollHeight + \'px\'"><scr' + 'ipt type="text/javascript" src="https://gist.github.com/' + gistId + '.js"></sc'+'ript></body></html>'; | |
var doc = iframe.document; | |
if (iframe.contentDocument) doc = iframe.contentDocument; | |
else if (iframe.contentWindow) doc = iframe.contentWindow.document; | |
doc.open(); | |
doc.writeln(iframeHtml); | |
doc.close(); | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For raw texts you have to change
var gistId = scope.gistId;
byvar gistId = attrs.gist;
Also remember to fill the username like
<div data-gist="pushlink/1a47d8b9710cd4e9e604"></div>