我用基本的JavaScript让这个iframe工作:
<iframe id="upload_iframe" name="upload_iframe" onLoad="uploadDone();"></iframe>
当 iframe 的内容加载完毕时,触发 uploadDone();
方法。
在 Angular 中如何实现相同的效果?我想在 iframe 加载时调用控制器上的函数,但是到目前为止我还没有看到 ng-onload
。
评论一年前的问题。 对于存在多个iframe的情况,我需要绑定“onload”事件。 我采用了这种方法。
指令
APP.directive('iframeOnload', [function(){
return {
scope: {
callBack: '&iframeOnload'
},
link: function(scope, element, attrs){
element.on('load', function(){
return scope.callBack();
})
}
}}])
控制器
APP.controller('MyController', ['$scope', function($scope){
$scope.iframeLoadedCallBack = function(){
// do stuff
}
}]);
文档对象模型(DOM)
<div ng-controller="MyController">
<iframe iframe-onload="iframeLoadedCallBack()" src="..."></iframe>
</div>
如果你使用的是 Angular 2+,那么很简单:
<iframe (load)="uploadDone()"></iframe>
没有全局函数,适用于多个iframe。
window.uploadDone=function(){
/* have access to $scope here*/
}
code
<div ng-repeat="item in items">
<iframe src="{{item.url}}" onload="iframeLoaded(item)" /> - Leon如果有人到了这里,ng-onload 插件是解决这个问题的完美方案。它不会污染全局命名空间,并且在您只想调用一个简单的作用域函数时,不需要创建一次性指令。
<div #iframeContainer></div>
ts...
@Component({
selector: 'app-iframe-onload',
templateUrl: './iframe-onload.component.html'
})
export class IframeOnload implements AfterViewInit {
@ViewChild('iframeContainer') iframeContainer: ElementRef;
ngAfterViewInit(): void {
this.injectIframe();
}
private injectIframe(): void {
const container = this.iframeContainer.nativeElement;
const iframe = document.createElement('iframe');
iframe.setAttribute('width', '100%');
iframe.setAttribute('src', 'https://example.com/');
iframe.setAttribute('height', 'auto');
iframe.setAttribute('frameBorder', '0');
iframe.addEventListener('load', this.iframeOnLoadtwo);
container.appendChild(iframe);
}
public iframeOnLoadtwo(): void {
console.log('iframe loaded...');
}
}
return scope.callBack(element);
这样我就可以在我的函数中读取元素属性了。 - Pandaioloscope.$on('$destroy', function() { element.off('load'); })
。请注意不要更改原文意思,尽可能使翻译通俗易懂。 - ra00l