I have often seen, developers come across a requirement to embed a YouTube video in an AngularJS application. In this post, we will learn to create a simple YouTube AngularJS directive and also to use some of the popular directive from the GitHub.
We will follow step by step approach to create YouTube custom directive. So let us start with create module and the controller.
- youtubedirective1.js
- var myApp = angular.module('myApp', []);
-
- myApp.controller('VideoController', function ($scope) {
- $scope.video = 'zRtPUIumXcY';
- });
Next we will create a custom directive with the isolated scope. Let us go ahead and create YouTube directive with the following characteristics:
- Directive will be used as an Element.
- Directive will work in the isolated scope.
- Directive replace property is set to true, such that user will not able to view the directive information in the browser.
- In the template, iframe is used to play the YouTube video.
- In the link function, we are watching the object passed to directive. Whenever value of object changed, directive will play the different video from YouTube.
Learn more about scopes in AngularJS custom Directives here.
By putting all above together, directive is created as shown in the listing:
- myApp.directive('angularYoutube', function($sce)
- {
- return {
- restrict: 'E',
- scope:
- {
- video: '='
- },
- replace: true,
- template: '<div style="height:300px;"><iframe style="overflow:hidden;height:100%;width:100%" width="100%" height="100%" src="{{url}}" frameborder="1" allowfullscreen></iframe></div>',
- link: function(scope)
- {
- scope.$watch('video', function(newVal)
- {
- if (newVal)
- {
- scope.url = $sce.trustAsResourceUrl("http://www.youtube.com/embed/" + newVal);
- }
- });
- }
- }
- })
As you might notice in above listing that in the template, we are using the iframe to play the YouTube video. Also we are watching the value passed to the directive and constructing the URL using the $sce service of AngularJS.
On the view, angular-youtube directive can be used as shown in the
listing:
- <divng-controller="VideoController">
- <angular-youtubevideo="video"></angular-youtube>
- </div>
As of now, we should able to play a video in AngularJS application. Right now we are passing hard coded video code from the controller. We can allow user to pass the video code, just by using an input textbox as shown in the
listing:
- <divng-controller="VideoController">
- <inputtype="text" ng-model="video" placeholder="enter video code here to play" />
- <hr/>
- <angular-youtubevideo="video"></angular-youtube>
- </div>
Here we have created a very simple custom AngularJS directive to embed YouTube video in the AngularJS application.
For advanced scenarios, you may want to use
Angular YouTube Embed. I find it very useful for advanced scenarios. I hope you find this post useful. Thanks for reading.