Troubleshooting: Issue with AngularJS Image onload directive - "this" reference not functioning properly?

I have a custom directive that looks like this:

.directive('ngImageOnLoad', function () {

    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('load', function() {

                  scope.$apply(function (){
                      scope.$eval(attrs.ngImageOnLoad);
                  });

                  event.preventDefault();

            });
        }
    };
})

The HTML img tag using the above directive is shown below:

<img src="images/abc.jpg" ng-image-on-load="onImageLoad(this)" />

In my controller, I have defined the function imageOnLoad as follows:

    $scope.imageOnLoad = function(theImg)
    {
        console.log("theImg is: " + theImg); //This prints [Object Object]
        console.log("theImg.src: " + theImg.src); //This prints UNDEFINED!!
    }

Question:
I am facing an issue where the 'this' reference is not working properly. Why is the image's src attribute returning as undefined in the function imageOnLoad?

Answer №1

Just finished creating a fiddle exclusively for you. Take a look at this link.

              Let's run this code block:
                  //scope.$eval(attrs.ngImageOnLoad);
                  $parse(attrs.ngImageOnLoad)(scope, {'element': element[0]});
              });

Answer №2

To access the target property from the event object, you can utilize the following code snippet:

.directive('ngImageOnLoad', function () {

    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('load', function(evt) {

                  scope.$apply(function (){
                      scope.$eval(attrs.ngImageOnLoad, { $element: evt.target});
                  });

                  evt.preventDefault();

            });
        }
    };
})

Here is an example of how to use it in HTML:

<img src="images/abc.jpg" ng-image-on-load="onImageLoad($element)" />

In your controller, you can define a function like this:

$scope.imageOnLoad = function(theImg)
{
    console.log("theImg is: " + theImg); //This prints [Object Object]
    console.log("theImg.src: " + theImg.src); 
}

Answer №3

If you desire something specific, utilize the $event feature (reference). Access the element using one of the event's methods (reference), for example:

<img src="images/abc.jpg" ng-image-on-load="onImageLoad($event)" />

Also:

$scope.onImageLoad = function($event) {
    console.log("theImg.src: " + $event.target.src);
}

Update:

As mentioned in the feedback, accessing $event in this manner is not correct. The proper method, as previously pointed out by pixelbits and Kasper Lewau, involves using $eval. For thoroughness, I am including it here as well:

The link function should be adjusted to:

link: function(scope, element, attrs) {
    var cb = $parse(attrs.ngImageOnLoad);
    element.bind('load', function(event) {
        scope.$apply(function() {
            cb({'$event':event});
        });
        event.preventDefault();
    });
}

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

Enhance User Experience with a Responsive Website Dropdown Menu

Currently, I am focused on enhancing the responsiveness of my website and I realized that having a well-designed menu for mobile view is essential. To address this need, I added a button that only appears when the screen size is 480px or lower, which seems ...

Identify the location of the mouse and activate a specific function based

Tracking the x-coordinate of the mouse is crucial in this scenario. When the mouse approaches a specific threshold (250px) towards the left edge of the window, it should trigger the function "openNav." The function should close when the mouse moves away fr ...

Guide on implementing a bootstrap loading spinner during the process of retrieving data from an external api

Is there a way to use the bootstrap load spinner to mask the delayed information retrieval from a url and enhance the website's interactivity? ...

What is the order of execution for AngularJS directives?

When using an AngularJS custom directive that executes a function, followed by a regular directive like ng-repeat, which one takes precedence in execution? For instance, if I have a select element with a custom multi-select directive and an ng-repeat dire ...

Error in Nestjs Swagger: UnhandledPromiseRejectionWarning - The property `prototype` cannot be destructed from an 'undefined' or 'null' object

Currently, I am in the process of developing a Nestjs REST API project and need to integrate swagger. For reference, I followed this repository: https://github.com/nestjs/nest/tree/master/sample/11-swagger However, during the setup, I encountered the foll ...

Toggle the visibility of an element using a checkbox in JavaScript

In my scenario, there are 8 checkboxes where only one is checked by default. If you click on the unchecked checkboxes twice, the table linked to them will hide. Ideally, I want the unchecked checkboxes to be hidden by default and the checked one to be sh ...

Displaying JavaScript - Nothing to Echo in PHP

Using PHP to echo a JavaScript block, I have encountered an error message. echo "<script language='javascript' type='text/javascript'> jQuery(document).ready(function($){ var $lg = $('#mydiv'); ...

What is the reason for npm and yarn to download multiple versions of jquery?

For the purpose of investigating how package managers like npm, yarn, and cnpm work in Node.js, I conducted an experiment. During the test, I came across two packages: jquery-dreamstream and jquery.tree. Both of them have a dependency solely on jquery wit ...

What is the best way to compare two date strings with the format dd/mm/yyyy using JavaScript?

When attempting to compare a "Date" type of data with an "Any" type of data, the comparison is not functioning as expected. The date is retrieved in the following code: var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); v ...

Italian calendar conversion for the react-multi-date-picker library

I recently integrated the react-multi-date-picker into my project, utilizing the multiple mode feature. However, I encountered an issue when trying to display the Italian calendar based on the language setting. Despite using locale="it", the calendar was n ...

What is the best way to add hidden columns in Telerik Grid MVC3?

I'm currently working with a grid where I need to hide certain columns using the following code: foreach (var attr in grid.Attr) .Columns(columns => { columns.Bound(attr.key) .Width(attr.width) .Visible(attr.isVisi ...

Sending data from a bespoke server to components within NextJS

My custom server in NextJS is set up as outlined here for personalized routing. server.js: app.prepare() .then(() => { createServer((req, res) => { const parsedUrl = parse(req.url, true) const { pathname, query } = parsedUrl ...

Encountered an issue with locating the module 'webpack-cli/bin/config-yargs' while attempting to run webpack-dev

Encountering an error while trying to start the webpack dev server with the command provided below. Despite suggestions that it could be due to outdated webpack versions, I am confident that all components are up to date: [email protected] [email ...

My locale NUXT JavaScript files are being blocked by Content Security Policy

I've been working on implementing CSP headers for my website to ensure data is loaded from trusted sources. However, I'm facing an issue where CSP is blocking my local JS files. Here's a snippet from my nuxt.config.js: const self = 'lo ...

Retrieve the element that is currently being hovered over within the same nested selector

I am facing a challenge in selecting the currently hovered element with a nested selector. The ".frmElement" class is used as the selector. When I hover over the ".frmElement" element at a certain level, all the previous selector elements display the hover ...

Transferring data between various stages of the user interface

As a newcomer to angularJs, I find myself facing an issue with two forms existing in different UI states (URLs) labeled as Step 1 and Step 2. The process requires filling up Step 1 and moving to the next step by clicking the NEXT button, which then leads t ...

Implementing jQuery and JavaScript validation for email addresses and usernames

Are the online validations being used incorrectly or is there a serious issue with them? I came across an example of a site using jQuery validation, but when I entered "44" for a name and ##@yahoo.com for an email address, no warning appeared. I haven&apo ...

Clear out a collection in backbone.js

I am looking to clear out a collection by removing each item in sequence. this.nodes.each(function(node){ this.nodes.remove(node); }, this); The current method is ineffective as the collection length changes with each removal. Utilizing a temporary arr ...

Choosing the right framework for implementing push notifications can be a critical decision. Should

I am currently working on a Java application that requires the server to send push notifications to the client every one second. To achieve this, I am using HTML5 server-sent events for one-way communication from the server to the client. However, my conce ...

What are the steps to ensure synchronous angular ajax calls?

function SubmitIdeaEvaluation(evaluationForm, ideaId, stageId, isEvaluated) { return $http({ url: SparkApp.FormEvaluation.SubmitIdeaEvaluation, method: "POST", contentType: "application/x-www-form ...