AngularJS - Triggering functions on image load event

I have been on a quest to find the best way to handle the onload event for images in Angular using jqLite. I came across this question, but I am looking for a solution that involves directives.
Therefore, the approach below is not satisfactory to me:

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

since it is within a controller and not a directive.

Answer №1

Introducing a versatile directive inspired by Angular's 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 an image finishes loading, the expression in the sb-load attribute is executed within the current scope alongside the load event, accessed as $event. Here's an example of its usage:

HTML

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

JS

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

Disclaimer: "sb" serves as a prefix for my custom directives in this context.

Answer №2

Great news! The jqLite's bind method is performing admirably. Here's how it works:

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

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

Next, we create a 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" event captured
                // Now we can perform specific actions:

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

Check out this example with visual aids: http://jsfiddle.net/5nZYZ/63/

Answer №3

AnguCJS Version 1.7.3 has introduced the ng-on-xxx directive:

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

While AngularJS already has directives like ngClick for many events, using ngOn may not always be necessary. However, there are some events that AngularJS does not currently support, and future updates may introduce new event possibilities based on DOM standards.

To learn more, you can refer to the AngularJS ng-on Directive API Reference.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Easily transfer files from your browser application to your Windows applications such as Outlook or printer queues using a simple drag and

I am attempting to transfer a downloaded file from a web browser to a Windows application (such as Outlook or a printer queue) by dragging and dropping. While I can successfully drop the file onto the desktop or any other file explorer location, I face iss ...

Exploring the Worldwide Influence of TypeScript, React, and Material-UI

I am currently following an official tutorial on creating a global theme for my app. In my root component, I am setting up the global theme like this: const themeInstance = { backgroundColor: 'cadetblue' } render ( <ThemeProvider theme ...

Using Meteor methods in a Meteor and Ionic application: A guide

After building the web app with Meteor, I am now looking to develop a new app utilizing both Meteor and Ionic technologies. My goal is to leverage the existing Meteor methods in my Ionic app without duplicating efforts for mobile development. Any suggestio ...

What is the proper way to implement ng-click in a link call within a directive?

http://plnkr.co/edit/Ry8gkozAaudhlmdPPQie?p=preview In the plunkr example provided, I am experimenting with creating a directive that can display different templates based on the presence of attributes on the directive element. <my-dir></my-dir& ...

Unable to fetch valid JSON from a different domain using JQuery and AJAX

I'm having trouble accessing a JSON api from a specific adult-themed website. I've been trying to make it work but so far no luck. You can find my code snippet in this jsfiddle: http://jsfiddle.net/SSqwd/ and here is the script: $.ajax({url: &ap ...

Button Hover Effect: Transition with Style

I am trying to implement a one-second transition from the default color scheme to the hover color for a Button element in Material UI. I am using the transitions.create(props, options) method as described in this article: https://medium.com/@octaviocoria/c ...

Why is adding a div to Facebook posts using JQuery failing due to dynamic loading?

I have been experimenting with the mouseover feature to enhance a Facebook group by adding additional content. Upon testing the DIV class, I realized that after the initial 10 or so instances of DIVs with the class storyInnerWrapper, the text stopped being ...

Manipulating the content of a specific row's table cells with a text box in jQuery Datatables

I am working with a jQuery datatable that consists of only one column. Every time a row is selected, a panel opens with a text box that automatically populates with the name of the selected td. I am trying to figure out how to edit the name of the selected ...

The div height adjustment peculiarities in IE7 and IE8 are causing quite a stir

I recently encountered a problem with my HTML/JS code that I thought was simple. The code is designed to expand the size of a div on mouseover and then collapse it back on mouseout. Here's how the code looks: CSS: .sign-in-up { position: absolut ...

How do I add a new item to an object using Ionic 2?

example item: this.advData = { 'title': this.addAdvS2.value.title , 'breadcrumb': this.suggestData.breadcrumb, 'price': this.addAdvS2.value.price ...

Improving Angular factory's counter with socket.io integration

I am currently working on a solution to automatically update the number of incoming data. I have set up a system to listen for incoming messages and count them in a factory: angular.module('app') .factory('UpdateCounter', ['s ...

Learn the process of adding and concealing items within an Ionic framework

I have a side menu and I need to modify the item displayed based on the user's status. For example, if the user is connected, then the "My Account" item should be visible. But if the user is not connected, then the "My Account" item should be hidden ...

unable to fix slideshow glitch after multiple cycles

I've encountered an issue with my custom JavaScript picture scroll. After 3-4 photo changes, the script crashes the page unexpectedly. I'm not sure what is causing this problem! Can someone provide assistance? Below is the code snippet: <di ...

Is Window.navigator malfunctioning on different browsers in Mac OS?

I'm attempting to access the navigator function in my project to share a specific URL, but I'm facing difficulties accessing it on Mac OS when using browsers other than Safari. Is there a solution to this issue? Below is the function I created f ...

How can we best understand the concept of custom directives using the link method?

As a beginner in AngularJS, I am looking to implement an autocomplete feature for text input. My JSON data is stored in JavaScript and I need help simplifying the process. Can you provide me with a straightforward solution? The specific requirement is to ...

Ways to generate arrays in Typescript

My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that ...

Leveraging PrimeFaces and the p:ajax component, trigger Ajax within an inputText field only when keystrokes lead to changes in the field

I am currently utilizing PrimeFaces and have a p:inputText field that requires updating certain components on the view based on the most recent keystroke within that p:inputText. Below is the code snippet: <p:inputText value="#{customerLController.surn ...

React Alert: Please be advised that whitespace text nodes are not allowed as children of <tr> elements

Currently, I am encountering an error message regarding the spaces left in . Despite my efforts to search for a solution on Stack Overflow, I have been unable to find one because my project does not contain any or table elements due to it being built with ...

Bootstrap typehead not activating jQuery AJAX request

I am attempting to create a Twitter Bootstrap typehead using Ajax, but nothing seems to be happening. There are no errors and no output being generated. Here is the jQuery Ajax code I have implemented: function CallData() { $('input.typeahea ...

Selecting a default option in Angular when the value is present and repeated

My goal is to pass a parameter in the URL to a page where a select element is populated dynamically. The parameter that needs to be passed is customerProfile.id. I want to find this id in the select options and have it selected by default. How can I achiev ...