我试图通过角度设置iframe内容高度
我有类似的东西
<iframe id='iframe' width='100%' height='600px' data-ng-init="init('iframe')"
src='http://test.com' />
Run Code Online (Sandbox Code Playgroud)
在我的控制器中
$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
}
Run Code Online (Sandbox Code Playgroud)
如何通过控制器设置iframe内容高度?
谢谢!
您的代码中的一些观察:
ng-init不是的equivalient $(window).on("load", function(){...}),有关详细信息,ng-init在这里:https://docs.angularjs.org/api/ng/directive/ngInit.这就是为什么你得到undefined了x和y,因为当执行代码的iframe尚未加载.
在angular中,从控制器访问DOM不是一个好主意,而是考虑在指令中进行那些操作.
如果你从angularjs开始,我建议你尽量不要使用jQuery.
在你的情况下,我认为你想要的是定义一个指令,iframeSetDimentionsOnload并在那里设置高度.我会在几分钟内给你举个例子.
你的iframeSetDimensionsOnload指令:
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);
})
}
}}])
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
<iframe iframe-set-dimensions-onload src='http://test.com' />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13391 次 |
| 最近记录: |