Skip to content

Instantly share code, notes, and snippets.

@mikaturunen
Created January 31, 2015 09:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikaturunen/f0b45def06bc83ccea9e to your computer and use it in GitHub Desktop.
Save mikaturunen/f0b45def06bc83ccea9e to your computer and use it in GitHub Desktop.
One way of hooking a callback from Angulars specific scope to HTML elements onload event
// There is no direct way of binding angular to elements onload event as commonly the HTML elements onload="" attribute looks into the
// Javascript global name space (window.*) which is a big no-no. It used to be the norm back in the day of how to do things but with
// modern frameworks like AngularJs and the such the approach has changed a lot.
// This is just one example (and by no means the only way) of how to get Angular behave nicely with HTML elements onload event. As
// <iframe onload="test()"> looks into window.test for a callback we need to bound the onload event to look into provided angular scope
// for the callback.
// NOTE: Written in ES6
/* global angular */
/* jslint node: true */
/* jshint esnext: true */
"use strict";
/**
* Creates an directive that allows angular scope bound callbacks to be executed on HTML elements onload event through the custom
* 'element-onload' attribute.
*
* Solves case:
* <iframe src="www.google.com" onload="callbackGlobalFunction()"></iframe>
*
* Example usage:
* <iframe src="www.google.com" element-onload="angularScopeCallback()"></iframe>
*/
var elementOnloadDirective = () => {
return {
restrict: "A",
scope: {
callback: "&elementOnload"
},
link: (scope, element, attrs) => {
// hooking up the onload event
element.on("load", () => scope.callback());
}
};
};
elementOnloadDirective.$inject = [ ];
elementOnloadDirective.directiveName = "elementOnload";
angular
.module("foobar", [ ])
.directive(elementOnloadDirective.directiveName, elementOnloadDirective);
@mikaturunen
Copy link
Author

Before

Works only if the callback is in global Javascript space, no-no!

    <iframe src="www.google.com" onload="callbackFromAngularScope()"></iframe > 

After

Fetches the callback from provided angular scope and voila~

    <iframe src="www.google.com" element-onload="callbackFromAngularScope()"></iframe > 

Published just as an example as quite many have asked how to get the above example to work in the cleanest possible way. This is just one solution and hopefully it'll help someone :) Have a good weekend folks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment