Adjusting size and framing of image upon page load using angular directive

I have created a directive that is responsible for rescaling and cropping an image based on its height and width.

angular.module('starter.directives', ['starter.controllers']).directive('styleImage', function () {
return {
    restrict: 'A',
    link: function preLink(scope, elem, attr) {
        elem.on('load', function () {
            styleImage(elem[0])
        });
    }
};

This "styleImage" function calculates the element's width and height to rescale and crop the image accordingly. I use the directive in the following way:

<img ng-src="{{user.image_path }}" class="user-image" style-image
                             id="{{'user'+user.user_id}}">

Everything works fine except for the fact that when the page loads, there is a slight delay before the directive kicks in to rescale and crop the image. As a result, the images initially appear with their original dimensions. I am wondering if there is a way to make sure the directive runs before the image finishes loading. If this is possible, how can I achieve it?

Answer №1

The order of events in Angular is as follows:

1- Routes detect the requested URL through the browser.

2- A Http request is made to retrieve the view templateUrl specified in your routing.

3- The View is then displayed on the page.

4- Any directives present on the view are triggered.

It is therefore common to first see the image and then observe it being cropped.

A possible solution could be to utilize a template within your directive, like so:

HTML

<style-image my-src='user.image_path'></style-image>

Directive

angular.module('starter.directives', ['starter.controllers']).directive('styleImage', function () {
return {
  restrict: 'E',
  scope{
    mySrc:"="
  },
  link: function preLink(scope, elem, attr) {
    var img= document.createElement('img');
    img.setAttribute('src',scope.mySrc)
    styleImage(img)
    elem.append(img);
   }
 };
})

Answer №2

check out these recommended links

Recommended Link

Suggested link1

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

Problem with Express.js serving dynamically generated index.html page

Currently, I'm immersing myself in a practice project to grasp the concepts of express and webpack with react and react router. My goal is to make sure all server requests are directed to index.html to avoid encountering "Cannot GET" errors when navig ...

Unable to locate the hidden element

Attempt to access the attribute of a shadow element resulted in encountering ElementNotVisibleException Element with CSS input[type='checkbox'] is not present on screen <checkbox _ngcontent-ebv-c14="" label="User Access" ng ...

Is there a way to modify the appearance of a block element and transmit a parameter to a PHP function?

It might seem like I'm overthinking things, but I am trying to achieve two goals with the HTML code provided. First, when a user selects an option, I want to toggle the display style of the leaderTable from hidden to visible if it meets certain criter ...

Forced line break at particular point in text

I would love to implement a line break right before the "+" character, either using css styling or through a different method. Is this task achievable? #myDiv{ width: 80% } #myP{ c ...

Editing content in place with JQuery, without the need for additional plugins

Currently, I am attempting to implement an edit-in-place control using Jquery without any plugins. My desired functionality is as follows: Upon clicking a paragraph, it should convert into an editable text area. Once the user clicks out of the paragraph (l ...

Unlock the secret: Using Javascript and Protractor to uncover the elusive "hidden" style attribute

My website has a search feature that displays a warning message when invalid data, such as special characters, is used in the search. Upon loading the page, the CSS initially loads like this: <div class="searchError" id="isearchError" style="display: ...

Customizing Your JQuery.awesomeCloud.plugin with a Tooltip Functionality using jQuery

Is it possible to integrate a jQuery Tooltip feature when hovering over specific words in a word cloud? I am currently using [jQuery.awesomeCloud.plugin]:https://github.com/indyarmy/jQuery.awesomeCloud.plugin If there is an alternative method to add toolt ...

Implementing Multiple Shared Footers in Rails 3

Looking for a solution to display unique footers in Rails? For instance, displaying one footer on the homepage and another footer on the rest of the site. Has anyone successfully implemented this before? I was considering using an if statement based on th ...

What is the process for importing a Kaggle dataset into Elasticsearch?

Having just started with elasticsearch, I am venturing into creating a movie search application. My plan involves sourcing data from kaggle and integrating it into my locally set up elasticsearch at localhost:9200. Upon visiting the localhost link, I came ...

What could be causing the createReadStream function to send a corrupted file?

My current task involves generating a file from a URL using the fs module to my local system. Initially, everything seems successful. However, when attempting to post this file into a group using the createReadStream() function, I encounter an issue where ...

Displaying the most recent queries retrieved from a search API

Our web application built on angular.js utilizes a REST search API to query users within the system. The endpoint for searching users is: search/user?q='abc' Upon revisiting the web application, we aim to display the user's recent search ...

Ways to Access a Variable from One Controller to Another Controller without Utilizing Scope

Just starting out with angularjs, I have an issue that needs quick solutions. How do I pass a variable from one controller to another without using scope or Service? ...

Issue with Opacity in IE8

The layer opacity works well in Firefox and Chrome, but struggles in IE8. $('document').ready(function () { $('.out-of-stock').each(function () { $('.productImage', $(this)).css('opacity', '.25'); ...

React 18 introduces a new feature, ReactDOMClient.createRoot(), which allows for hot module replacement with Webpack. This allows developers to update components in real time without

After upgrading React to version 18, I encountered a console error with my Webpack dev server when the hot module replacement triggers and injects new JavaScript code: Warning: You are calling ReactDOMClient.createRoot() on a container that has already be ...

Default behavior in Fullcalendar 6 allows for rendering links on both days of the month and weekdays

Is there a way to customize the rendering of days and weekdays in Fullcalendar React? Currently, they are displayed as links by default (<a>{dayContent}</a>), but I'm looking to have them rendered as <div> or <span>. Any sugges ...

Could anybody provide some assistance with JavaScript?

<div id="toggler" class="toggler"> <div id="toggler" class="line1"></div> <div id="toggler" class="line2"></div> <div id="toggler" class=& ...

Can anyone suggest a method to preview a specific image before uploading on Internet Explorer?

One issue I am encountering is that Internet Explorer does not support the Filereader function in JavaScript. My solution was to send the file via ajax to the server, which would then respond with the file's content. Do you think this approach could w ...

The default props defined in the React component's child element are taking precedence over the custom props supplied by the parent component

The font size is being displayed as 20 and the color as 'red', instead of the font size being 12 and the color being 'blue' as specified in the parent component. However, the fontWeight as 'bold' is showing correctly. I have ...

Changing Highcharts Donut Chart Title Text via Legend Item Click in React

Utilizing React. In my Highcharts donut chart, there are 5 legend items of type 'number' and a 'title text' (also type: number) displayed at the center. The title text represents the sum of all the legend items. However, when I click o ...

Use Vue.js to display a class when the input is invalid and not empty

How can I apply a has-error class when an input is invalid and not empty in vue.js? <div class="form-group"> <input type="email" id="loginEmail" name="loginEmail" v-model="loginEmail" required> <label for="loginEmail">Email</label ...