Skip to content

Instantly share code, notes, and snippets.

@tleunen
Last active May 1, 2019 00:51
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tleunen/5277011 to your computer and use it in GitHub Desktop.
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.
<!-- In your template -->
<div data-gist="{{gistId}}"></div>
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();
};
});
@celiovasconcelos
Copy link

For raw texts you have to change var gistId = scope.gistId; by var gistId = attrs.gist;
Also remember to fill the username like <div data-gist="pushlink/1a47d8b9710cd4e9e604"></div>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment