Skip to content

Instantly share code, notes, and snippets.

@mpchadwick
Created November 27, 2013 03:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpchadwick/7670014 to your computer and use it in GitHub Desktop.
Save mpchadwick/7670014 to your computer and use it in GitHub Desktop.
This directive lets you easily embed YouTube videos in your ng-app with out the performance suckiness of YouTube's iFrame embed code (which forces users to download 400K of data before even pressing play). This directive first finds and displays the video's thumbnail based on the id attribute, and only swaps in the iframe when the thumbnail is c…
directive('nonSuckyYoutubeEmbed', function factory() {
var directiveDefinitionObject = {
restrict: 'E',
template: '<div style="position: relative;">' +
'<img src="img/play-btn.png" style="position: absolute; left: 50%; top: 50%; width: 48px; height: 48px; margin-left: -24px; margin-top: -24px; cursor: pointer;" alt="Play" />' +
'<img src="http://i.ytimg.com/vi/{{id}}/0.jpg" style="width: 100%; height: auto; display: inline; cursor: pointer" alt="" />' +
'</div>',
scope: {
id: '@id'
},
link: function(scope, element, attrs) {
attrs.$observe('id', function(id) {
if(id) {
var height = (attrs.height) ? attrs.height : 390;
var width = (attrs.width) ? attrs.width : 640;
var paddingBottom = ((height / width) * 100) + '%';
var iframeStyle = 'position: absolute; top: 0; left: 0; width: 100%; height: 100%';
var iframeContainerStyle = 'position: relative; padding-bottom: '+paddingBottom+'; padding-top: 30px; height: 0; overflow: hidden;'
element.on('click', function() {
var v = '<iframe type="text/html" style="'+iframeStyle+'" width="'+width+'" height="'+height+'" src="http://youtube.com/embed/'+id+'?autoplay=1" frameborder="0" />'
var newHTML = '<div style="'+iframeContainerStyle+'">' + v + '</div>';
element.html(newHTML);
});
}
});
}
};
return directiveDefinitionObject;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment