Adding video src with Angular

Well, well, well… if you try to add a video to your page and use Angular to set its URL… you may discover that Angular doesn’t allow you to do that. This is because Angular blocks some possible hacking attempts like setting manual html to the page or so with a service called $sanitizer, interestingly, Angular allows you to set an image “src” or the href of a link without issues, but blocks you if you try to add the “src” of an HTML5 video element. To be able to add the video URL this way you need to tell Angular that this is a safe operation using Angular’s Strict Contextual Escaping Service. There are different ways in which you can make use of such service to solve this:

Solution 1: Global config with a WhiteList of URLs

This approach will add to the SCE service config a list of safe URLs so that SCE allows them to pass, it also supports some regular expressions:

angular.module('myApp', []).config(function($sceDelegateProvider) {
 $sceDelegateProvider.resourceUrlWhitelist([
   // Allow same origin resource loads.
   'self',
   // Allow loading from our assets domain.  Notice the difference between * and **.
   'http://srv*.assets.example.com/**']);
 })

Solution 2: Add a filter

Ok, the theoretical manual way of doing this is by telling SCE that such URL is safe, to do so you have to call the service’s method “trustAsResourceUrl()”, doing so in the View won’t work, parsing the URL on the Controller may work, but if you have a list of videos in an ng-repeat parsing them previously may be a bit tedious, so, a better approach for this seems to be adding a filter:

angular.module('myApp')
  .filter('trustUrl', function ($sce) {
    return function(url) {
      return $sce.trustAsResourceUrl(url);
    };
  });

The filter will just get a URL and return it as safe so that SCE allows it to pass, now on the view you only need to call the filter:

<video ng-src={{ imageHref | trustUrl }}">

Extra! Solution 3. Just calling SCE

Well this is also seen on the previous example and on Angular’s Documentation but just in case it’s not enough clear, this is the method you need to call to tell SCE that a URL is safe:

app.controller("controllerName", function($sce){ // Don't forget to inject SCE on your controller if you want to access it!!!
    $scope.trustedUrl = $sce.trustAsResourceUrl(myUrl);
});

And then you call it from the View:

<video ng-src={{ trustedUrl }}">

PD: Thanks to chriz and fiznool for these solutions.

6 thoughts on “Adding video src with Angular

Leave a Reply

Close Bitnami banner
Bitnami