Create a YouTube AngularJS Directive
16,376
With Angular 1.2, you need to inject $sce
service and trustAsResourceURL
the src
of an iframe
.
Demo: http://plnkr.co/edit/0N728e9SAtXg3uBvuXKF?p=preview
.directive('youtube', function($sce) {
return {
restrict: 'EA',
scope: { code:'=' },
replace: true,
template: '<div style="height:400px;"><iframe style="overflow:hidden;height:100%;width:100%" width="100%" height="100%" src="{{url}}" frameborder="0" allowfullscreen></iframe></div>',
link: function (scope) {
scope.$watch('code', function (newVal) {
if (newVal) {
scope.url = $sce.trustAsResourceUrl("http://www.youtube.com/embed/" + newVal);
}
});
}
};
});
Also see: Migrate from 1.0 to 1.2 and related question.
Author by
Jonathan Hindi
Updated on June 04, 2022Comments
-
Jonathan Hindi about 2 years
I created the following AngularJS directive to embed youtube videos:
// A Simple youtube embed directive .directive('youtube', function() { return { restrict: 'EA', scope: { code:'=' }, replace: true, template: '<div style="height:400px;"><iframe style="overflow:hidden;height:100%;width:100%" width="100%" height="100%" src="http://www.youtube.com/embed/{{code}}" frameborder="0" allowfullscreen></iframe>' }; });
When I call it from my template
<youtube code="r1TK_crUbBY"></youtube>
, I get the following error:Error: [$interpolate:noconcat] Error while interpolating: http://www.youtube.com/embed/{{code}} Strict Contextual Escaping disallows interpolations that concatenate multiple expressions when a trusted value is required. See http://docs.angularjs.org/api/ng.$sce
I can't identify what's wrong with the directive in the
{{code}}
expression. -
Jonathan Hindi over 10 yearsI tried the above and I added the missing comma for the end of the template: line, Now it's not giving any error, but it doesn't show the video embedded, inspecting the element I see the src attr empty.
-
musically_ut over 10 years@JonathanHindi It works here: plnkr.co/edit/0N728e9SAtXg3uBvuXKF?p=preview with Angular 1.2 How are you using the directive in the template?
-
Jonathan Hindi over 10 yearsThanks now it works, I was using the <youtube code="{{code}}"></youtube> I thought I need to pass it with the currently brackets to be evaluated first then pass the actual value to the directive. but it seems that I was wrong.
-
fmquaglia over 10 yearsYou saved me lots of try and error. Thanks @musically_ut