Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the iframe content height in my case?

I am trying to setup the iframe content height through angular

I have something like

<iframe id='iframe' width='100%' height='600px' data-ng-init="init('iframe')" 
 src='http://test.com' />

in my controller

 $scope.init = function(id) {
            console.log($('#'+ id))  -> show my iframe
            var x= $('#'+ id)..contentWindow.document.body.scrollHeight;
            console.log(x) -> gives me undefined

            var y = $('#'+ id)..contentWindow;
            console.log(y) -> give me undefined too 
        }

How do I set the iframe content height through my controller?

Thanks!

like image 991
FlyingCat Avatar asked Sep 17 '14 00:09

FlyingCat


People also ask

How do I change the size of an iframe dynamically?

Using the window. postMessage() method, we can safely communicate between the iframe and the parent window. That way, we can send a height value from the iframe to the parent window. Then, in the parent window, we can set a simple script to dynamically update the height of the iframe.

How do I keep a iframe aspect ratio?

In the HTML, put the player <iframe> in a <div> container. In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.


1 Answers

Some observations from your code:

  1. ng-init is not the equivalient of $(window).on("load", function(){...}), more information about ng-init here: https://docs.angularjs.org/api/ng/directive/ngInit . That's why you are getting undefined for x and y, because when that code is executed the iframe hasn't been loaded yet.

  2. In angular is not a good idea to access the DOM from the controller, consider doing those sort of operations in a directive instead.

  3. If you are starting with angularjs I would recommend you to try not to use jQuery.

In your case I think that what you want is to define a directive like iframeSetDimentionsOnload and set the height there. I will give you in example in a few minutes.

Your iframeSetDimensionsOnload directive:

yourApp.directive('iframeSetDimensionsOnload', [function(){
return {
    restrict: 'A',
    link: function(scope, element, attrs){
        element.on('load', function(){
            /* Set the dimensions here, 
               I think that you were trying to do something like this: */
               var iFrameHeight = element[0].contentWindow.document.body.scrollHeight + 'px';
               var iFrameWidth = '100%';
               element.css('width', iFrameWidth);
               element.css('height', iFrameHeight);
        })
    }
}}])

Use it like this:

<iframe iframe-set-dimensions-onload src='http://test.com' />
like image 118
Josep Avatar answered Sep 19 '22 18:09

Josep