AngularJS controller function call when html5 video ends

I have a video on the main page of my application that plays at startup. When the video ends, I would like to use some CSS 3 transitions to move the page.

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

At the end of the video, I would like to be able to call the 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) { replicationService.replicate(); }); 

My controller looks like this:

 'use strict'; var app = angular.module('app', false); app.controller('homeCtrl', function ($rootScope){ this.data = {}; var ctrl = this; this.video = function () { console.log("video done"); } }); 

If I put a console.log() in the <video onended=""> element, it will print it. If I try to call ctrl.video() , 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 ng-click="ctrl.video()" and I click on the video player that it prints.

+5
source share
2 answers

I ended up using Angular UI Utils , which has a common event binding element. This allowed me to bind an event that AngularJS does not fail. Using the following line ui-event="{ ended : 'ctrl.video()'}" , I was able to call my function when the video ended, which gave me the desired behavior.

+6
source

I'm a little new to Angular, so I don't know how best to fix it, but I can at least tell you why it doesn't work.

ng-click="ctrl.video()" works because ctrl is defined in the controller area. All ng attributes are executed within the control area. But onended is a regular built-in attribute of the HTML5 event handler, so it runs in the global Javascript scope, not the controller scope. There is no ctrl.

(I'm not sure how var ctrl = this; invokes the definition of ctrl in the controller scope, but apparently it does. Still learning Angular ...)

+2
source

Source: https://habr.com/ru/post/1215053/


All Articles