Search code examples
javascriptjqueryangularjsiframeangularjs-ng-repeat

Iframe load event inside an AngularJs ng-repeat


I'm trying to create a directive so that I can do some element manipulation upon the load of an iFrame inside of an ng-repeat.

The below CodePen contains an iframe both inside and outside of an ng-repeat. The directive initializes without a problem but the load events never fire.

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

Any pointers greatly appreciated.


Solution

  • You can use angular element ready method for that. Try the following please.

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