Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a YouTube AngularJS Directive

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.

like image 231
Jonathan Hindi Avatar asked Dec 07 '13 23:12

Jonathan Hindi


People also ask

Can we create custom directive in AngularJS?

Angular provides the ability to create custom directives. A directive is basically a custom HTML attribute. It is a way to extend HTML vocabulary and modify the behavior of the DOM and your Angular application.

What are the directives of AngularJS?

AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

What are directives in Angular 7?

Directives in Angular 7 are Typescript class which is declared with decorator @Directive. These are the Document Object Model (DOM) instruction sets, which decide how logic implementation can be done.


1 Answers

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.

like image 155
musically_ut Avatar answered Oct 21 '22 01:10

musically_ut