How to set the height of iframe content in my case?

I am trying to adjust the height of iframe content using 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 to set the height of iframe content through my controller?

Thanks!

+7
angularjs iframe
source share
2 answers

Some observations from your code:

  • ng-init not equivalent to $(window).on("load", function(){...}) , more information about ng-init here: https://docs.angularjs.org/api/ng/ directive / ngInit . This is why you get undefined for x and y because when this code is executed, the iframe is not loaded yet.

  • In angular, it is not recommended to access the DOM from the controller; consider doing these operations in a directive.

  • If you are starting with angularjs, I would recommend that you try not to use jQuery.

In your case, I think you want to define a directive, for example iframeSetDimentionsOnload , and set the height there. I will give you an 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 as follows:

 <iframe iframe-set-dimensions-onload src='http://test.com' /> 
+9
source share

If your iframe :

 <iframe id='iframe' width='100%' height='600px' src='http://test.com' /> 

Your controller might look something like this:

 AppName.controller('someNameCtrl', ['$scope', '$window', function ($scope, $window) { $scope.width = '100%'; $scope.height = '600px'; angular.element($window).bind('resize', function(){ $scope.width = $window.innerWidth; $scope.height = $window.innerHeight; console.log($scope.width, "x", $scope.height); // manuall $digest required as resize event // is outside of angular $scope.$digest(); }); }); 

Then you can play with style as a variable

 <iframe id='iframe' ng-style="{ height: height, width: width }" src='http://test.com' /> 
0
source share

All Articles