jvandemo.com

How to make embedded videos in your AngularJS and ui-router app fluid with fluidvids.js

Introduction

user

Jurgen Van de Moere

Follow @jvandemo

ui-router, angular, fluidvids.js, 2 minutes, youtube, vimeo

How to make embedded videos in your AngularJS and ui-router app fluid with fluidvids.js

Posted by Jurgen Van de Moere on .
Featured

ui-router, angular, fluidvids.js, 2 minutes, youtube, vimeo

How to make embedded videos in your AngularJS and ui-router app fluid with fluidvids.js

Posted by Jurgen Van de Moere on .

featureimage

Fluidvids.js is awesome!

It makes your embedded videos fluid so they blend perfectly in your responsive design.

View a live demo here.

The caveat

Unfortunately there is a caveat when working with AngularJS and ui-router.

Single page applications load their content without refreshing the page so the fluidvids.init() method is not called when the state changes.

This means that when the application state changes, embedded videos are not processed by fluidvids.js.

The solution

Fortunately there is an easy fix by adding the following code to your AngularJS application:

(function () {

  /**
   * Register handler that runs fluidvids render method
   * when state has changed
   *
   * This takes care of making embedded videos fluid.
   */
  function registerSuccessHandler($rootScope, $window, $timeout) {

    // Make sure fluidvids is available
    if($window &&
      $window.fluidvids &&
      $window.fluidvids.init &&
      $window.fluidvids.render) {

      // Initialize fluidvids with settings you need
      $window.fluidvids.init({
        selector: ['iframe', 'object'],
        players: ['www.youtube.com', 'player.vimeo.com']
      });

      // Let fluidvids re-render on state change
      $rootScope.$on('$stateChangeSuccess', function () {
        $timeout(function(){
          $window.fluidvids.render();
        });
      });

    }

  }

  // Inject dependencies;
  registerSuccessHandler.$inject = ['$rootScope', '$window', '$timeout'];

  // Export
  angular
    .module('app')
    .run(registerSuccessHandler);

})();

Make sure you replace app in the last command with the name of your AngularJS application module.

Fluidvids.js will now process all videos dynamically when the state of your application changes.

Now you can enjoy the beauty of fluid videos in your AngularJS single page applications!

Happy embedding!

user

Jurgen Van de Moere

Front-end architect at The Force. Gymnast. Dad. Family man. Creator of Angular Express.