Consider replacing the custom attribute directive in Angular with a different directive

I am currently working on a custom attribute directive to handle a src-like attribute that represents a relative path to a directory.

The directory path is stored in a global variable (let's call it mydir).

This attribute should be replaced with an ng-src combined with the directory path.

Here is how I intend to use it:

<md-icon my-src="cake.svg"></md-icon>
<md-icon my-src="{{ anExpression }}"></md-icon>
<md-icon my-src="{{::onTimeBinding}}"></md-icon>

In addition, I want this functionality to work beyond Angular Material usage.

Thank you for your assistance!

Edit:

I apologize for any confusion. My intention is for the mySrc directive to be usable across all types of elements. It should be converted to ng-src with the base directory. I have created a Plunkr, but it seems to not be functioning correctly. The current code looks like this:

app.directive("mySrc", function() {

  return {
    restrict: "A",
    compile: function(element, attrs) {

      return {
        pre: function(scope, element, attributes) {
          var baseUrl = 'http://dummyimage.com/';
          attributes.$set("ng-src", baseUrl + attributes.mySrc);
        }
      }

    }
  }
});

Usage example:

<img my-src="100" />
<img my-src="{{ expr }}" />
<img my-src="{{:: oneTimeExpr }}" />

We also need to ensure compatibility with the last two options.

Answer №1

Your method seems to be effective, however, your approach may need a slight adjustment. Instead of replacing my-src with ng-src, consider changing it to src, as ng-src serves a similar purpose to what you are aiming for. The key is to ensure the tag is rendered correctly by the browser.

To achieve this, utilize

attributes.$set("src", baseUrl + attributes.mySrc);
. Although this solution is not dynamic in nature.

Referencing the source for ng-src, implement $observe to monitor changes in your attribute.

pre: function(scope, element, attributes) {
    var baseUrl = 'http://dummyimage.com/';
    attributes.$observe("mySrc", function(value) {
        attributes.$set("src", baseUrl + attributes.mySrc);
    })
}

<button ng-click="expr = '200'">Test dynamic</button>

A test button has been added to demonstrate dynamic updates. Through $observe, any modifications to the mySrc attribute will automatically update the src attribute with the new URL.

http://plnkr.co/edit/vogwUGai8iMavk5elDVB?p=preview

Answer №2

To execute your necessary action, you can utilize the directive implementation below:

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

app.directive('myImage', function ($compile) {
    return {
        restrict: 'A',
        replace: true,
        scope: true,
        template: '<li><img ng-src="{{ imageUrl }}" /></li>',
        link: function (scope, element, attrs) {
          let baseUrl = 'http://placeholder.com/';
          console.log(attrs);

          scope.imageUrl = baseUrl + attrs.myImage;
        }
    };
});

For a demonstration of this in action, check out this example

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

Setting maxFontSizeMultiplier for all Text components

Is there a way to apply the prop maxFontSizeMultiplier={1} to all instances of <Text/> in my app without the need for a custom component? ...

By default, the text area element in Vue or Nuxt will send a message to the console

Every time I include a textarea html element in my Vue/cli or Nuxt projects, this message appears in the console. Is there a way to prevent this message from showing up in the console? <textarea rows="5" cols="33"> This is a textarea. < ...

What is the best way to prevent content from jumping when using Ajax.load functions?

Currently, I have implemented a chat function on the page. Unfortunately, I am facing an issue where new messages from user B are not automatically loading on the chat window of user A. To address this problem, I added the following code: <script type= ...

Encountering unexpected behavior with the .data() method

I'm encountering an issue with my code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv= ...

Strange outcome in Three.js rendering

Is it possible to correct the reflection issue around the cycles? I noticed some strange results on my object and I've attached pictures to illustrate the problem. Current result in Three.js: https://i.sstatic.net/iJbpm.jpg https://i.sstatic.net/hv ...

Exploring the world of Single Page Application SEO and the wonders of infinite scroll with

Looking to revamp our website, which features a feed similar to Pinterest. Considering moving away from the messy jQuery code and leaning towards either AngularJS or Backbone+Marionette for a more structured approach. The site is user-generated with a stro ...

Retrieve the nth element from an array using a function that requires 2 arguments

During my coding journey, I encountered a challenge that has proven to be quite tricky. The task in question goes as follows: Create a function that accepts an array (a) and a value (n) as parameters Identify and store every nth element from the array in ...

Observing API requests to "/undefined" and "/null" endpoints within AngularJS framework

Upon loading my Angular (1.4.9) application, I encounter a console error that reads as follows: /undefined: Failed to load resource: the server responded with a status of 404 (Not Found). Another similar error appears with /null instead of /undefined. Af ...

html carousel not updating in popover

I've been attempting to create a popover with a bootstrap carousel, where the carousel items are dynamically generated and appended from a script. Despite my efforts, I have successfully displayed the carousel but struggle to append the items. I' ...

Utilize Javascript to create a function that organizes numbers in ascending order

Is there a way to modify this code so that the flip clock digits appear in ascending order rather than randomly? $( '.count' ).flip( Math.floor( Math.random() * 10 ) ); setInterval(function(){ $( '.count' ).flip( Math.floor( Math.rand ...

The initial return value of $(document).height may be inaccurate, but is accurate upon recalculation

I am working on implementing a pop-up screen and I would like to darken the background when it opens. Below is the Javascript code: $(document).on('click', '.item', function(){ $("#popUp").css("display" , "block"); ...

Transfer a JavaScript value to PHP via POST method without the need for submitting or refreshing the page

My website includes a Google Map feature that updates geocoordinates when the marker is dragged and displays the address. Currently, JavaScript is passing the X and Y values to an HTML "ID" using the "GET" method. However, I now need to pass these values u ...

Can we set a restriction on the maximum number of children a particular div can contain?

I'm trying to find a way to restrict the number of children in a div. The concept is that there is a selected commands div where you can drag and drop available commands (essentially buttons) from another div called available commands. However, I wan ...

Using the same ng-model to show distinct values in two separate input fields

I have a form with a dropdown list that loads data using the ng-model="placeid". When a user selects an option from the dropdown, I want to display the selected place's latitude (place.lat) in an input box. Here is the dropdown list code: <select ...

The concept of undefined functions and the use of dependency injection may not always align

Recently starting with AngularJs, I am honing my skills by developing a single page Todo Application. However, I have encountered an issue while trying to load a localStorage factory that I intend to use for this project. Currently, I am stuck on the error ...

What are the available search options in the MarkLogic Search API to limit keyword searches from including specified values within JSON properties?

Is there a way to limit the MarkLogic search API keyword search so it does not include specific JSON property values? For example, can I search for keyword 'x' in all properties of JSON documents except for those with values of 'p', &ap ...

Enhance your dynamic content with jQuery/AJAX through customized CSS styling

Below is the jquery (3.1.1)/ajax request that I am using: $.ajax({ type: "POST", url: "pref.php", dataType: "text", data: { groupe_id: groupe_id, action: "getProducts" }, cache: false, error: function(html){ ...

Displaying files from Google Drive on a web page

How can I display documents saved on my drive on a webpage with the ability for users to download them directly? Any advice on how to achieve this would be greatly appreciated. Thank you! ...

Verifying user authentication within Angular applications

I am developing a unique angular application that utilizes a directive named ng-auth to manage the visibility of elements based on the user's login status. Here is an example: <div ng-auth="!isAuthenticated()"> <a href="/login">Log-in ...

Preventing long int types from being stored as strings in IndexedDB

The behavior of IndexedDB is causing some unexpected results. When attempting to store a long integer number, it is being stored as a string. This can cause issues with indexing and sorting the data. For instance: const data: { id: string, dateCreated ...