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

非常感谢任何指点。

您可以为此使用 angular 元素就绪方法。请尝试以下方法。

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,来自 docs.

on() - Does not support namespaces, selectors or eventData

您可以在 DOM 节点 上使用本机 addEventListener,因此您的 link 函数会喜欢这样:

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