Issue with ng-repeat directive not functioning

Let's dive into this directive:

.directive('img', function () {
    return {
        restrict: 'E',
        link: function (scope, elem, attr) {
            if (attr.src && attr.type === "extension"){

                var url = "chrome-extension://" + chrome.runtime.id + attr.src
                // console.log(url)

                elem[0].removeAttribute('src')
                // elem[0].setAttribute("src", url)
                // elem[0].dataset.ngSrc = url
                console.log(elem[0])
                console.log(elem[0].src)

            }

        }
    };
})

In the file profile.html:

          <tr ng-repeat="integration in profile.integrations">
             <td>
                  <!-- <h3>{{integration.provider}}</h3> -->
                 <img type="extension" src="/images/icons/{{integration.provider}}.png" alt="" width="50px">
             </td>
         </tr>

Despite my efforts, the console log shows that the src is not being removed or replaced by the URL. It seems to be related to ng-repeat as it works perfectly with another image.

Answer №1

You are essentially replicating one of Angular's convenient directives that was created for scenarios where an expression is used in the src attribute. Instead of using src, opt for ng-src and eliminate the need for your img directive

Check out the ng-src documentation: https://docs.angularjs.org/api/ng/directive/ngSrc

Inserting Angular markup like {{hash}} into a src attribute won't function as intended: Initially, the browser will fetch from the URL with the literal text {{hash}} until Angular substitutes the expression within {{hash}}. The ngSrc directive resolves this issue.

<img type="extension" 
     ng-src="/images/icons/{{integration.provider}}.png" alt="" width="50px">

As mentioned by runTarm in the comments, this doesn't incorporate the chrome-extension protocol into the image URL. To achieve that, you need to take two steps:

  1. Incorporate chrome-extension into the AngularJS whitelist to prevent Angular from appending unsafe: to the URL
  2. Add the expression to ng-src to include the protocol

Whitelist addition

//adapted from http://stackoverflow.com/a/15769779/560593
var app = angular.module( 'myApp', [] );
app.config( ['$compileProvider', function( $compileProvider ) {   
    //includes chrome-extension in the whitelist
    $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension):/);
]);
app.run(function($rootScope){
    //assign the id to the rootScope for usage in expressions
    $rootScope.extensionUrl = "chrome-extension://"+chrome.runtime.id;        
});

HTML

<img ng-src="{{extensionUrl}}/images/icons/{{integration.provider}}.png" alt="" width="50px">

JSFiddle

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

Using Vue.js to handle asynchronous functions with undefined variables

My Vue.js application is facing a problem where an async function is passing a variable as undefined even though it's properly defined before the function call. The async function FETCH_DATA in my Vue.js application is defined like this: async [FETCH ...

Encountering a syntax error with the spread operator while attempting to deploy on Heroku

I'm encountering an error when attempting to deploy my app on Heroku: remote: SyntaxError: src/resolvers/Mutation.js: Unexpected token (21:16) remote: 19 | const user = await prisma.mutation.createUser({ remote: 20 | data: { r ...

Firefox won't trigger the `beforeunload` event unless I interact with the webpage by clicking on it

In my quest to handle the beforeunload event in Firefox, I've encountered a small hurdle. It seems to be working smoothly, but only if the user physically interacts with the page by clicking on it or entering text into an input field. Below is the co ...

React-native - Dropdownpicker - Error: Unable to retrieve label for selected choice

I'm encountering an issue with DropDownPicker in my react-native project during page load Here is the code snippet where I am using DropDownPicker: <DropDownPicker items={[ { la ...

I am having difficulty retrieving the JSON object that was sent by the servlet

$(document).ready(function() { var path = null; console.log('${pageContext.request.contextPath}/loadfile'); $.ajax({ dataType: "json", url: '${pageContext.request.contextPath}/loadfile&apos ...

Issue: [ng:areq] The argument 'HelloController' is not defined as a function, it is displayed as undefined

Struggling to integrate Angular with Django has been quite a challenge for me. After finally managing to make it work, I encountered yet another error. Each time I load the application, the following error message pops up: Error: [ng:areq] Argument ' ...

Implementing custom CSS styles for HighCharts API pie chart drilldown labels

I successfully created a pie chart using highcharts and configured the chart with the following options: chart: { type: 'pie', }, In order to change the width of the text on the chart, I added the following options which force e ...

Learn how to dynamically clear and update source data in jQuery autocomplete for enhanced functionality

Here is a snippet of my jQuery code. In this code, 'year' refers to the form input tag ID, and 'years' is an array variable containing all the year values. I have set this array as the source for autocomplete, which works fine. However, ...

The Stripe card element seems to be missing from the form

I'm a newcomer to angularjs and currently working on integrating version 3 of the stripe api into my angular application. I followed the steps provided on the stripe website, but faced an issue when trying to incorporate their code which is primarily ...

Step-by-Step Guide on Resetting Versions in Package.json

I currently have around 20 react projects, each with their own package.json files. These package.json files contain various packages and their versions: "@material-ui/core": "4.11.4", "@material-ui/icons": "4.11.2", ...

Why is AngularJS redirection not retrieving the value from window.localStorage?

After utilizing local storage, I encountered an issue where upon logging in and being redirected to the myprofile page, the local storage value was not loading properly. Instead, I was getting a null value. It wasn't until I manually reloaded the page ...

Recent npm dependency error found in local development setup after functioning properly

Today, I have been diligently working on a local project and a local npm package that is being used in the project. Everything was running smoothly up until now - my project and the library were functioning without any issues when installed with npm instal ...

The function Router.use is looking for a middleware function, but instead received an object in node.js /

I encountered an issue while trying to setup routing in my application. Whenever I attempt to initialize a route using app.use() from my routes directory, I receive an error stating that Router.use() requires a middleware function but received an Object in ...

Is it possible to link an HTML select element to a changing array in JavaScript?

Let's say I have an empty HTML select element. <select id="options"> </select> Can I link a JavaScript array to this select so that when the array is modified, the select options update accordingly? Alternatively, do I need to resort to ...

How can you reference the immediate selector object using jQuery?

I'm currently delving into the realm of jQuery and decided to create a test page equipped with the following code: <a id='encode' href='javascript: void(0)'>encode</a> | <a id='decode' href='javascr ...

How can I identify when a node/express ajax request is received?

I have set up a node/express server that sends the ajax-start.html file. Within this file, there is a script that enables ajax requests to be made to the server. Everything functions correctly in this setup. However, I am looking to enhance this process by ...

"Retrieve and transfer image data from a web browser to Python's memory with the help

Is there a way to transfer images from a browser directly into Python memory without having to re-download them using urllib? The images are already loaded in the browser and have links associated with them. I want to avoid downloading them again and ins ...

Exploring new ways to add line breaks in Angular UI drop-down boxes

Hello everyone, I'm having an issue with the drop-down toggle feature in ui.bootstrap. Instead of aligning properly in my menubar, it's creating a new line. I've set up a plunker to demonstrate the problem. You can see that when I insert a ...

What is the best way to halt a CSS transition using JavaScript when dealing with an image?

I am facing an issue while attempting to create a basic CSS transition using JavaScript. The goal is for the start button to trigger the movement of an element, based on the duration of the keyframe animation. Then, clicking the end button should make the ...

Is it possible to modify or delete the question mark in a URL?

Currently, I am working on implementing a search bar for one of my websites hosted on Github. Below is the code I have written for the search bar: <!-- HTML for SEARCH BAR --> <div id="header"> <form id="newsearch" method ...