Search code examples
jqueryangularjsiframeangularjs-directivejqlite

change the content of an iframed page in Angularjs


I need to dynamically iframe various html pages in AngularJS and then change parts of their html content. I have created a directive and it iframes just fine but my problem is that I can't access the contents of the iframed pages just the way we do it in jQuery! Neither I can do so using jqLite! Can anyone help?

Here is how the directive looks like

myApp.directive('pageiframe', ['$scope','$location', function($scope,$location) {
    var src=  some URL // I get this somehow
    return {
        restrict: 'C',
        replace: true,
        template: "<iframe src="+src+" height='2000px' width='100%' frameborder='0'></iframe>",
        link: function(scope, elem, attrs) {
        var targetIframe=elem[0] // here we get the iframe but then i can't change its html content 
        elem.contents().find('#element').html('change') // this doesn't work!
        }
      }
    }])

p.s I have already put the jQuery link on top of the main page and elsewhere I can use it just fine!


Solution

  • Similar to using document.ready or window.onload you can't access the contents of the iframe document until it loads.

    link: function(scope, elem, attrs) {
        elem.on('load', function(){
           elem.contents().find('#element').html('change') ;
        }
    }