Home AngularJS - Image "onload" event
Reply: 2

AngularJS - Image "onload" event

Cherniv Published in 2013-07-09 12:14:53Z

I've been searching for an answer to simple but not trivial question: What is a right way to catch image' onload event in Angular only with jqLite? I found this question , but I want some solution with directives.
So as I said, this is not accepted for me:

.controller("MyCtrl", function($scope){
    // ...
    img.onload = function () {
        // ...

because it is in controller, not in directive.

SamBarnes Reply to 2014-11-06 14:28:22Z

Here's a re-usable directive in the style of angular's inbuilt event handling directives:

angular.module('sbLoad', [])

  .directive('sbLoad', ['$parse', function ($parse) {
    return {
      restrict: 'A',
      link: function (scope, elem, attrs) {
        var fn = $parse(attrs.sbLoad);
        elem.on('load', function (event) {
          scope.$apply(function() {
            fn(scope, { $event: event });

When the img load event is fired the expression in the sb-load attribute is evaluated in the current scope along with the load event, passed in as $event. Here's how to use it:


<div ng-controller="MyCtrl">
  <img sb-load="onImgLoad($event)">


  .controller("MyCtrl", function($scope){
    // ...
    $scope.onImgLoad = function (event) {
        // ...

Note: "sb" is just the prefix I use for my custom directives.

Cherniv Reply to 2017-01-31 17:39:00Z

Ok, jqLite' bind method doing well its job. It goes like this:

We are adding directive' name as attribute in our img tag . In my case , after loading and depending on its dimensions , image have to change its class name from "horizontal" to "vertical" , so directive's name will be "orientable" :

<img ng-src="image_path.jpg" class="horizontal" orientable />

And then we are creating simple directive like this:

var app = angular.module('myApp',[]);

app.directive('orientable', function () {       
    return {
        link: function(scope, element, attrs) {   

            element.bind("load" , function(e){ 

                // success, "onload" catched
                // now we can do specific stuff:

                if(this.naturalHeight > this.naturalWidth){
                    this.className = "vertical";

Example (explicit graphics!): http://jsfiddle.net/5nZYZ/63/

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.532154 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO