programing

iFrame의 각도, onLoad 함수

lastcode 2023. 2. 9. 21:58
반응형

iFrame의 각도, onLoad 함수

기본 JavaScript로 동작하는 iframe이 있습니다.

<iframe id="upload_iframe" name="upload_iframe" onLoad="uploadDone();"></iframe>

이로 인해 메서드가 트리거됩니다.uploadDone();iframe의 내용이 로드되었을 때.

Angular에서 어떻게 같은 일을 합니까?iframe이 로드되었을 때 컨트롤러에서 함수를 호출하고 싶은데 아직 볼 수 없습니다.ng-onload지금까지는 이해돼요.

1년 된 질문에 대한 코멘트.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
    }
}]);

<div ng-controller="MyController">
    <iframe iframe-onload="iframeLoadedCallBack()" src="..."></iframe>
</div>

컨트롤러 내의 함수를 다음과 같이 정의해 보십시오.

window.uploadDone=function(){
  /* have access to $scope here*/
}

Angular 2+를 사용하는 사용자는 다음과 같습니다.

<iframe (load)="uploadDone()"></iframe>

글로벌 함수는 없으며 여러 iframe에서 작동합니다.

이 문제를 해결하려면 ng-onload 플러그인이 가장 적합합니다.글로벌 네임스페이스를 오염시키지 않고 단순한 범위 함수를 호출하는 데 필요한 경우 일회성 지시문을 생성할 필요가 없습니다.

iframe을 동적으로 주입하는 경우 다음 작업을 수행할 수 있습니다.

html...

<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...');
}

}

언급URL : https://stackoverflow.com/questions/15882326/angular-onload-function-on-an-iframe

반응형