Utilizing the "ImagesLoaded" plugin within an event handler in AngularJS

If my page undergoes a re-render, I want to show a loading indicator. This is triggered by an event emitted from the re-rendered section.

Check out

Within my custom directive:

app.directive('pendingIndicator', function(){
    return {
        restrict: 'A',
        link: function(scope, element) {
            scope.$on('pending', function(){
                scope.imgLoad = imagesLoaded( element );
            });
        }
    };
});

However, attempting to wrap imagesLoaded() in an event listener ($on) or $watch results in an error being thrown.

Console Error Message:

TypeError: 'undefined' is not an object (evaluating 'eventie.bind')

Does anyone have an idea of what might be causing this issue and why it's not working as expected?

Answer №1

I successfully implemented the ImagesLoaded plugin, as demonstrated in this plunkr.

This is just a starting point to guide you. It would be ideal if you can refactor the logic of the ImagesLoaded plugin (eliminating the need for Jquery) and handle it purely within AngularJS.

To optimize how you listen for ImagesLoaded events, here is an adjusted directive code with additional comments and suggestions:

angular.module('myApp', []).
  directive('pendingIndicator', function(){
    return {
        restrict: 'A',
        link: function(scope, element) {
            // prepare the container for ImagesLoaded ... consider using
            // this directive on a parent element containing multiple images...
            scope.imagesLoaded = imagesLoaded(element);
            // initiate your progress/loading animation at this point
            // (or whenever the image loading process begins)
            scope.imagesLoaded.on('always', function() {
              console.log('always event: Triggered after all images have loaded or are confirmed broken.');
              // conclude the progress/loading animation for all images here, 
              // either collectively or individually in the progress event handler shown below
            });
            scope.imagesLoaded.on('done', function() {
              console.log('done event: Triggered after all images have successfully loaded without any issues.');
            });
            scope.imagesLoaded.on('fail', function() {
              console.log('fail event: Triggered after all images have been loaded with at least one broken image.');
            });
            scope.imagesLoaded.on('progress', function(instance, image) {
              console.log('progress event: Executed after each individual image finishes loading.', instance, image);
              // wrap up the progress/loading animation here or perform it for 
              // all images within the 'always' event handler above
            });

        }
    };
});

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

How can I utilize ng-repeat in AngularJS to iterate through an array of objects containing nested arrays within a field?

Here is the structure of an array I am working with: 0: {ID: null, name: "test", city: "Austin", UserColors: [{color: "blue"},{hobby:"beach"} ... ]} }... I am currently attempting to ng-repeat over this initial array in my code. However, when I tr ...

I am experiencing issues with the functionality of Node.js and Express routes

Recently diving into the world of Node.js, I'm encountering some challenges with connecting to my local host and working with MongoDB. It appears that the routes I've set up are being overlooked. To provide context, here's a snapshot of how ...

Ensure to update the canvas prior to the function finishing

Is there a way to update the canvas element while inside a JavaScript function without waiting for the function to return? It can be frustrating when you want to keep the function running but also need to update the canvas element in real time. ...

What could be causing the appearance of a mysterious grey box hovering in the upper left portion of my image and why is the code only adjusting the size of the grey box instead of the entire

I've been working on embedding some JavaScript into my Showit website to create a drag-and-drop feature that displays a collage/mood board effect. Everything is functioning correctly, but I'm running into issues with resizing the images. There&a ...

What strategies can be used to prevent state mutations?

I am facing mutability for the first time. My state items consist of an object with keys like id, and using allIds I am trying to update specific id items with a new date. However, all items are being changed simultaneously, which I believe is due to mut ...

Why does my Observable remain perpetually unfulfilled?

I recently started learning javascript and came across the Angular 2 Documentation where I discovered that Promises can be replaced with Observables. While experimenting with a simple code, I noticed that in addition to the expected result, I am also getti ...

Is there a way to retrieve and store a JSON object from a URL using JavaScript and jQuery?

I have a PHP page that is returning a JSON object in the correct format, like this: [ { "name":"Users", "parent":"null", "children":[ { "name": "adsd", "parent": "Users", "children": [] } , { "name": "ca", "p ...

The issue persists with the $slice function in MongoDb

I am attempting to retrieve records using an aggregate function in MongoDB, but I keep encountering the error message stating that the operator $slice is invalid: db.getCollection('test').aggregate( [ { $match: { 'subjectId': &apos ...

Leverage the power of JSON objects within your Angular.js application

Is it possible to request a JSON object, such as the one in employes.json file: {"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]} Then, how can I util ...

AngularJS using the ng-controller directive

I am presenting the following HTML code excerpt... <!DOCTYPE html> <html lang="en-US" ng-app> <head> <title>priklad00007</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angula ...

I am currently working on obtaining images that are saved by their URL within a PHP file. These images are located within a directory named "images."

My code is incomplete and not functioning as expected. $.get("museums.php",function(data,status){ var response=''; //console.log(data); var json = $.parseJSON(data); museums = json.museums; for(let m in museums) { $("#na ...

Ways to determine the presence of data in a web browser

I have a code snippet that displays each item in a separate column on the browser. What I want to achieve is to have another page where, upon clicking a button, it will check if that specific item is present on the page. The page that displays the item: ...

Issues arise with objects disappearing when zooming out in Three.js

In my current three.js project, I have encountered an issue with the z position of my camera. Whenever the z position is set too high, the scene turns completely black when zooming out, which is not the desired outcome. Specifically, with camera.position. ...

When clicking on a checkbox's assigned label, Chrome and IE may experience delays in firing the change event

When a user checks a checkbox under a specific condition, I want to display an alert message and then uncheck the checkbox. To achieve this, I am utilizing the click function on the checkbox to internally uncheck it and trigger necessary events. I have a ...

Troubleshooting Node.js and MySQL: Queries failing to return expected results

I'm currently using Node.js to connect with MySQL. One issue I'm facing is that a SELECT query is not returning the desired result. However, when I use an INSERT query, it works perfectly! To tackle the problem with the SELECT query, I decided ...

Converting PHP code to utilize AJAX in JS

Within the confines of a single file (invasions.php), I have the following code: <!DOCTYPE html> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'> <head> <meta http-equiv='con ...

The function was triggered upon the form loading, instead of being activated when the button was clicked

The issue I am facing is that in the code snippet below, the function readCSV() is not being triggered when buttons for filepath1 and filepath2 are clicked. The function is only executed on form load. I was expecting it to work on button click as well. I ...

Triggering an action with JQuery when clicking on a button within an Angular

I need to open a new link whenever a column in my datatable is clicked. Below is the code for my datatable which fetches data through an ajax call- <table datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="featuretable row-border compact ...

Tips for fixing an error encountered when running a react native project for the first time

I am encountering some errors while attempting to run this project for the first time and I am unable to resolve them. Below is the content of the package.json file: { "scripts": { "start": "expo start", "andro ...

Concatenate data received from PHP to a JavaScript variable and return it

In my current app development project, I have the following code snippet. The variable valdat is sent to a specified URL, processed through a PHP file, and then returned to the app. How can I add the data displayed in the alert message to another variabl ...