Calling AngularJS controller function when html5 video ends


I have a video on the homepage of my app which plays when I launch it. When the video ends I'd then like to use some CSS 3 transitions to move the page around.

<ion-view  hide-back-button="true" title="">
        <div class="home-video">
            <video autoplay="autoplay" ng-click="" aria-label="video of IBM logo" tabindex="-1" aria-hidden="true" poster="images/Hero_Final_Placeholder.gif" onended="">
                <source src="videos/video.mp4" type="video/mp4">
                <img src="images/video_backup.gif" title="Your browser does not support the video tag.">

At the end of the video I'd like to be able to call an angularJS Controller function.

'use strict';

angular.module('app', ['ionic']).config(function ($stateProvider, $urlRouterProvider) {

$stateProvider.state('home', {
  url: "/home",
  templateUrl: 'views/home.html',
  controller: 'homeCtrl as ctrl'
}).state('project', {
  url: "/project/:projectId",
  templateUrl: 'views/project.html',
  controller: 'projectCtrl'

 // Default view to show
$urlRouterProvider.when('', '/home');

}).run(function ($http, pouchDB, replicationService, $rootScope) {



My controller looks like:

'use strict';

var app = angular.module('app', false);

app.controller('homeCtrl', function ($rootScope){ = {};

var ctrl = this; = function () {

        console.log("video done");



If I put a console.log() in the <video onended=""> element it prints it out. If I try and call which contains the same console.log I get the following error:

Uncaught ReferenceError: ctrl is not defined

I know that ctrl is defined because if I add an ng-click="" and I click the video player it prints out.

Problem courtesy of: Sam Marland


Eventually what I did was use Angular UI Utils which has a generic event binder. This allowed me to bind to an event that AngularJS doesn't out of the box. Using the following line ui-event="{ ended : ''}" I was able to call my function when the video ended which gave me the desired behaviour.

Solution courtesy of: Sam Marland


I'm a bit new to Angular, so I don't know the best way to fix it, but I can at least tell you why it isn't working.

ng-click="" works because ctrl is defined in the controller's scope. All ng- attributes run within the controller's scope. But onended is a regular built-in HTML5 event handler attribute, so it runs in the global Javascript scope, not the controller's scope. There's no ctrl defined there.

(I'm not sure how var ctrl = this; causes ctrl to be defined in the controller's scope, but apparently it does. Still learning Angular...)

Discussion courtesy of: aldel

This recipe can be found in it's original form on Stack Over Flow.