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!
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.
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.
Some observations from your code:
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.
In angular is not a good idea to access the DOM from the controller, consider doing those sort of operations in a directive instead.
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' />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With