Bug in Iframe directive with Angular: issue with the src attribute

Encountering an issue with implementing an Iframe directive.

Status: Template:

<div class="externalIframe" iframe-src="external.html"></div>

Directive :

angular.module('project.directives', [])
   .directive('externalIframe', ['$rootScope', function($rootScope) {
      return {
        restrict: 'C',
        replace: true,
        transclude: true,
        scope: {
          src: '@iframeSrc', // utilizing data-binding from parent scope
        },
        template: '<iframe src="{{src}}" height="100%" width="100%" frameborder="0"></iframe>',
        link: function(scope, elem, attrs) {
          //elem.src = "dummy.html"; // not working either
        }
      }
    }])

Issue: Triggering 2 HTTP requests (2 iframe loading).

  • one to
    http://localhost:8000/app/{{src}}
    (iframe src not yet interpreted by angular)
  • one to
    http://localhost:8000/app/external.html
    (iframe src once interpreted by angular)

Looking to avoid the unnecessary first call. Any suggestions?

Attempted setting src programmatically in link or compile function with no luck in loading the iframe.

edit: jsFiddle added for bug demo with compile method => two requests are observed in network tab of firebug/chrome dev panel:

  • http://fiddle.jshell.net/_display/%7B%7Bsrc%7D%7D
  • http://fiddle.jshell.net/_display/external.html

Appreciate any assistance.

Answer №1

No directive is necessary in this case. Simply utilize ng-src on a real iframe element. Refer to the documentation for ng-src.

<iframe ng-src="external.html"></iframe>

Answer №2

By removing src from the iframe in the template and instead modifying the attribute in the link function using element.attr(), we can achieve the desired result:

return {
    restrict: 'E',
    require: '?ngModel',
    replace: true,
    transclude: true,
    template: '<iframe height="100%" width="100%" frameborder="0"></iframe>',
    link: function (scope, element, attrs) {
        element.attr('src', attrs.iframeSrc);
    }
};

Check out the Fiddle here: http://jsfiddle.net/5rYrw/

Answer №3

Instead of simply using 'link' in your code, consider utilizing the 'compile' function to modify the HTML before it is inserted into the DOM. This way, you can make changes to the source attribute directly rather than relying on the binding process.

Here's a breakdown of how things work with link: 1. First, compile is called with {{url}}, triggering an iframe request. 2. Then, link is called, replacing {{url}} with the actual URL, leading to a second call.

By opting for 'compile', you gain more control over modifying the src attribute yourself.

For further insights, take a look at http://docs.angularjs.org/guide/directive

Edit Feel free to explore this fiddle as well: http://jsfiddle.net/jbSx6/20/

return {
    restrict: 'E',
    require: '?ngModel',
    replace: true,
    transclude: true,
    template: '<iframe src="%url%" height="100%" width="100%" frameborder="0"></iframe>',
    compile: function (element, attrs, transclude) {
        console.log(element[0].outerHTML);
        element[0].outerHTML = element[0].outerHTML.replace('%url%',attrs.iframeSrc);
        console.log(element);
    }
};

<div ng-app="myApp">
   <div>display google in frame</div>
   <my-frame data-iframe-src="http://jsfiddle.net">test</my-frame>
</div>

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

Is there a way to conclude an Inquirer prompt depending on the response received?

My current project involves creating an application that presents a series of questions to gather information and generate an employee profile. This application is designed to be recursive, meaning that users will have the option to exit and terminate the ...

Does the Mirage addon work effectively in the ember.js tutorial?

Following the ember.js tutorial, I'm facing a roadblock at this particular stage: (especially when implementing the Mirage add-on). I've made changes to the mirage/config.js file as advised but still unable to display the Mirage data. Despite ...

Error occurred in child process while processing the request in TypeScript: Debug Failure encountered

I encountered the following error in TypeScript while running nwb serve-react-demo: Child process failed to handle the request: Error: Debug Failure. Expression is not true. at resolveNamesWithLocalCache (D:\Projects\react-techpulse-components& ...

Conceal an extended menu by clicking away from the container: a guide on implementing a code snippet

I'm working on a menu that opens a sub-menu section when clicked (let's call this container: "sub-menu"). I want the "sub-menu" to disappear if the user clicks outside of it, on the rest of the page. I found a solution on How do I detect a click ...

How to add page breaks with spacing and page numbers in HTML to PDF conversion?

Seeking assistance regarding adding spacing between page breaks within an HTML table to accommodate a page number at the bottom of each page. Below, I have depicted my current setup and what I aim to achieve. Is it feasible with the html2pdf library? http ...

Adding a checkbox to menu items in a ReactJS application can be accomplished by utilizing specific components

I have successfully created dynamic menus using a recursive function, and they are displaying in the correct order without any issues. Requirement: My current goal is to identify the last level of menus and assign a checkbox with the value corresponding ...

Having trouble parsing the JSON object values within the Error section of the Ajax call

When making an Ajax call to a rest web API, I encountered an error that I need help resolving. Here is the code snippet: $.ajax({ url: "/********/getbytitle('****')/items", type: "POST", contentType: "applicat ...

I am puzzled as to why it is searching for an ID rather than a view

Currently, I am attempting to navigate to a specific route that includes a form, but for some unknown reason, it is searching for an id. Allow me to provide you with my routes, views, and the encountered error. //celebrities routes const express = requir ...

Utilizing NextJs req.query parameter in Prisma for advanced query filtering

Currently, I am delving into the world of NextJS and experimenting with sending requests to an API while passing a parameter that is then used by Prisma to query the database. In order to achieve this, I've created a new file located at /api/posts/[s ...

Minimize or conceal iframe

This iframe contains a Google form that cannot be edited. I am looking for a way to close or hide this iframe, either through a button, a popup window button, or without any button at all. The $gLink variable holds the Google form link through a PHP sessio ...

Ways to adjust your selection to the space or new line before or after

$('button').on('click', function(){ const selection = window.getSelection(); selection?.modify('move', 'backward', 'word'); selection?.modify('extend', 'forward', 'to the next space ...

Search for all items that share the same identification numbers in JavaScript

Trying to parse through my students array to find all objects with matching ids and extract other property values from them has been challenging... Consider the following sample array: const students = [ {id: 1, name: 'Cal', location: &apos ...

Using infoWindows with multiple markers in Google Maps

i have developed a custom Google Maps application that pulls data from a CSV file. The functionality works well, but I am facing an issue with the infoWindow when looping through all the objects. It seems like the problem stems from the marker variable bei ...

I'm encountering an issue with my Angular CLI project where it's showing an error message that says "Module cannot be found."

Currently, I am diving into an Angular-cli tutorial. In one of my component TS files, there seems to be a problem with importing a class from another directory as it is not being recognized. Below is the content of my component file (display-user-data-for ...

Error: Unable to access property of an undefined value (ExpressJS/POST)

I have gone through all the similar questions but none of the solutions are working for me. I am facing an issue with my node js app where I am unable to print the input text from a form while using body-parser. Here is my index.ejs file: <fo ...

Error: [ngRepeat:iexp] The expected expression should be in the form of '_item_ in _collection_ [ track by _id_]' but instead received '"movie'

While testing my Rails/Angular app on the production Rails server, I encountered an error in my console that I am struggling to resolve. The specific error message reads: Error: [ngRepeat:iexp] Expected expression in form of '_item_ in _collection_[ ...

Changing the stroke color in between drawing on an HTML5 Canvas

I have been experimenting with a basic JavaScript snippet to showcase an unusual HTML5 canvas behavior I've encountered. Every 100ms, I am drawing the same set of strokes but in a different sequence. Strangely, some of the strokes change color interm ...

Retrieving numerous data points from the user interface

I am in the process of designing a user interface that includes various fields such as text boxes, dates, etc. It is important for users to be able to add values to these fields multiple times as needed. For example, a user fills out all the information ...

React JS BlueprintJS Date Range Picker not functioning as expected

I am struggling to implement a DateRangePicker using BlueprintJS on my component, following the instructions in the documentation. I also want to include a RangePicker similar to the one shown in this screenshot. I have successfully installed all the nece ...

What is the fastest and most effective method for identifying the Angular or AngularJS version that a website is utilizing?

During my time at work, I have inherited a collection of over 30 web sites and applications that were created using C#, ASP.NET, MVC, and AngularJS/Angular. These projects were developed and updated between the years of 2010 to 2018, with some being more r ...