Angular.js:在加载时更改Iframe高度&更改内容

时间:2015-10-07 21:16:32

标签: javascript angularjs iframe

我有一个角度应用,它将另一个页面动态加载到给定的iframe中。然后根据父页面的输入更改此iframe的范围。

我有角度代码将初始html加载到iframe中,并使用一段简单的javascript代码来更改窗口更改时的iframe大小。

我如何实现:

在iframe的初始加载以及内容的每次更改时,我想将iframe高度调整为内容(这样基本上没有滚动条可见,内容似乎是页面的一部分)。

我的代码片段:

使用iframe的HTML:

<div ng-app="cvForm" ng-controller="cvFormController">
    <iframe cvframe="" id="cv-output-frame" style="width: 100%; height: 1000px; border: none"></iframe>
</div>

将内容加载到iframe

/**
 * Load CV template
 */
cvFormApp.directive('cvframe', function($compile, $http, appConfig) {
    return function($scope, $element, tpl) {
      $http({
        url: appConfig.baseUrl + 'res/templates/mf_classic.html',
        method: 'GET'
      }).then(function(response) {
        var $body = angular.element($element[0].contentDocument.body), 
                    template = response.data;
        $body.append($compile(template)($scope)); //appended compiled element to DOM
      });
    };
});

调整窗口更改高度的代码:

function resizeIframe() {
    var oIFrame = document.getElementById('cv-output-frame');

    oIFrame.style.height = oIFrame.contentWindow.document.body.scrollHeight + 'px';   
    console.log('cv pane iframe resized to: ' + oIFrame.style.height);
}

document.getElementById('cv-output-frame').onload = resizeIframe; 
window.onresize = resizeIframe;

resizeIframe();

我玩过指令和观察声明,但我还是初学者,不知道如何开始。我的伪例程就像:

  1. 将内容加载到iframe
  2. 将watch-directive附加到iframe
  3. 初始载荷变化完成高度
  4. 在每个范围更改时调整高度以反映新内容(在许多情况下,高度不会受到影响,因为范围更改很小)
  5. 感谢任何提示并指出正确的方向!

1 个答案:

答案 0 :(得分:0)

假设您可以控制iframe并且两者都在同一个域中,我知道完成此任务的最佳方式是使用window.postMessage()方法。

基本上,在iframe调整大小的任何实例上,您都可以调用

window.parent.postMessage(yourMessage, 'http://yourdomain.com);

我可能会回发高度来设置包含iframe,但你可以传回任何东西。有一些安全问题,所以你一定要仔细研究这些问题,但它们应该很容易解决。然后在你的resize指令中:

angular.module('myApp.directives', [])
    .directive('resize', ['$window', function($window) {
        return {
            restrict: 'A',
            link: function resizeLink(scope, element, attributes) {
                angular.element($window).on('message', function(event) {
                    element.attr('height', event.data + 'px');
                });
            }
        };
    });
相关问题