簡體   English   中英

在AngularJs ng-repeat內部加載iframe事件

[英]Iframe load event inside an AngularJs ng-repeat

我正在嘗試創建一個指令,以便我可以在ng-repeat內加載iFrame時進行一些元素操作。

以下CodePen包含ng-repeat內部和外部的iframe。 該指令初始化沒有問題,但加載事件永遠不會觸發。

var app = angular.module('tester', []);

app.directive('iframeOnload', [function(){
return {
    scope: {
        callBack: '&iframeOnload'
    },
    link: function(scope, element, attrs){
      alert("Directive Init")
        element.on('load', function(){
          alert("Load Event Fired")
            return scope.callBack();
        })
    }
}}])

app.controller('MainCtrl', function($scope) {    

  $scope.tester1 = function (){
    alert("Testing 1")
  }

  $scope.tester2 = function (){
    alert("Testing 2")
  }

  $scope.theTemplate = [
            {
                Id: 1,                
                ElementId: 99,                                      
                Content: 'Element1',
                ElementHeight: 130,              
            },
            {
                Id: 2,
                ElementId: 98,                                      
                Content: 'Element2',
                ElementHeight: 320,              
            },
            {
                Id: 3,
                ElementId: 2,                                      
                Content: 'Element3',
                ElementHeight: 320,
            }];
});

<body ng-controller="MainCtrl">
    <iframe iframe-onload="tester2()"></iframe>
  <ul>    
    <li ng-repeat="element in theTemplate" id="li_{{element.Id}}"  style="position: relative; height:{{element.ElementHeight}}px;">
      <iframe iframe-onload="tester1()" scrolling="no" frameborder="0" style="width: 100%; height:{{element.ElementHeight}}px;" id="iframeElement{{element.Id}}"></iframe>
      {{element.Content}}
    </li>
  </ul>
  </body>

https://codepen.io/jibber4568/pen/agZxgP

任何指針都非常感激。

您可以使用角度元素就緒方法。 請嘗試以下方法。

app.directive('iframeOnload', [function(){
return {
    scope: {
        callBack: '&iframeOnload'
    },
    link: function(scope, element, attrs){
      alert("Directive Init")
        element.ready(function(){
          alert("Load Event Fired")
            return scope.callBack();
        })
    }
}}])

這是因為您沒有使用jQuery,因此AngularJs使用它自己的jqLit​​e,來自文檔

on() - 不支持名稱空間,選擇器或eventData

您可以在DOM節點上使用本機addEventListener ,因此您的鏈接函數將是這樣的:

link: function (scope, $element, attrs) {
  console.log('Directive Init');
  var element = $element[0];
  element.addEventListener('load', function () {
    console.log('Load Event Fired');
    return scope.callBack();
  }, { once: true });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM