Domanda

I have an event object whose data comes from a json, this event has an array of videos which I am trying to display as YouTube embeds. I am trying to use a directive to accomplish this but it is not working within the ng-repeat I am doing for the videos. This is the code of the directive:

app.directive('youtube', function($sce) {
  return {
    restrict: 'EA',
    scope: { code:'=' },
    replace: true,
    template: '<iframe width="560" height="315" src="{{url}}" frameborder="0" allowfullscreen></iframe>',
    link: function (scope) {
        scope.$watch('code', function (newVal) {
           if (newVal) {
               scope.url = $sce.trustAsResourceUrl("http://www.youtube.com/embed/" + newVal);
           }
        });
    }
  };
});

When I try to use it like this, then it doesn't works, the variable is not parsed if I use the curly brackets and it doesn't works either without them:

<div ng-repeat="video in event.videos" class="embed">
   <div youtube code="{{video}}"></div>
</div>

The {{video}} element has the id of the YouTube video, if I do this ng-repeat without the directive, the video ids print fine, so it is working but not parsing it when used within the directive.

Any help is appreciated, thanks in advance!

È stato utile?

Soluzione

try ng-src in your template

app.directive('youtube', function($sce) { return { restrict: 'EA', scope: { code:'=' }, replace: true, template: '', link: function (scope) { scope.$watch('code', function (newVal, oldVal) { // use newVal and oldVal console.log(newVal); // log it to see that it is passed if (newVal !== undefined) { scope.url = $sce.trustAsResourceUrl("http://www.youtube.com/embed/" + newVal); } }); } }; });

also, in your HTML, you don't need {{ }} around video, its already a variable on the scope

<div ng-repeat="video in event.videos" class="embed">
   <div youtube code="video"></div>
</div>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top