Reputation: 217
i have a url video links( http://www.youtube.com/watch?v=myvideoid) from my database that i want to embed into i frame using angular.
i have tried the code below but its not working
<iframe width="200" height="300" ng-src="http://www.youtube.com/embed/{{v_link}}" frameborder="0" allowfullscreen></iframe>
where {{v_link}}
is the column that stores the video in mysql database. any help please
Upvotes: 2
Views: 3939
Reputation: 19070
With $sce you can make the desired URL as trusted:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
});
app.filter('trustUrl', function($sce) {
return function(url) {
return $sce.trustAsResourceUrl(url);
};
});
app.directive('youtubePlayer', function() {
return {
restrict: 'E',
scope: {
header: '@',
video: '@'
},
transclude: true,
replace: true,
template: '<iframe ng-src="{{video | trustUrl}}"></iframe>',
link: function(scope, element, attrs) {
scope.header = attrs.header;
}
};
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS App</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<youtube-player video="https://www.youtube.com/embed/ZzlgJ-SfKYE" header="Url Description">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</youtube-player>
</body>
</html>
Upvotes: 2
Reputation: 7072
The error that you're getting is $interpolate:noconcat
. It states:
Strict Contextual Escaping disallows interpolations that concatenate multiple expressions when a trusted value is required. Source.
This means that you must use $sce and mark the desired URL as trusted. This would fix your problem:
angular
.module('myApp', [])
.controller('MainCtrl', function($sce) {
this.youtubeLink = $sce.trustAsResourceUrl('https://www.youtube.com/embed/N4ony2r0QFs');
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainCtrl as vm">
<iframe width="560" height="315" ng-src="{{ vm.youtubeLink }}" frameborder="0" allowfullscreen></iframe>
</div>
Another way, as stated in this answer, would be to create a custom filter which is specifically built to trust youtube URLs:
.filter('youtubeEmbedUrl', function ($sce) {
return function(videoId) {
return $sce.trustAsResourceUrl('https://www.youtube.com/embed/' + videoId);
};
});
You'd be using this filter anytime you want to embed a video, like this: ng-src="{{ vm.youtubeLink | youtubeEmbedUrl }}"
.
Upvotes: 2