Created
January 31, 2015 09:45
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Before
Works only if the callback is in global Javascript space, no-no!
After
Fetches the callback from provided angular scope and voila~
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!