Angular - append html through different frames wit

2020-02-29 10:50发布

问题:

My code have the main windonw and one iframe and each one with your module. A button in main window fires click event that should append html into iframe, the new html when appended into that should apply interceptors and directives properly, but it doesn't work! Angular javascript:

angular.module('module1',[]).controller('Controller1', function ($scope) {
  $scope.get = function(){
    $http.jsonp("some_url_here").success(function(html){
      $scope.content = html;
    });
  }
}).directive('click', function($compile) {
  return {
    link: function link(scope, element, attrs) {
      element.bind('click',function(){
        var unbind = scope.$watch(scope.content, function() {
        var div=document.getElementById("frame").contentWindow.angular.element("divId");
        div.append($compile(scope.content)(div.scope()));

          unbind();
        });
      });
    }
  }
});


angular.module('module2',[]).directive('a', function() {
  return {
    restrict:'E',
    link: function(scope, element, attrs) {
      console.log('ping!');
      console.log(attrs.href);
    }
 };
});

Html code:

<html ng-app="modile1">
  <div ng-controller="Controller1">
    <button type="button", ng-click="get('any_value')", click:""/> Load frame
  </div>

  <iframe id="frame" src="/please/ignore/this">
   <!-- considere the html as appended from iframe-src and contains ng-app="module2" -->
   <html ng-app="module2">
     <div id="divId">
      <!-- code should be inject here -->
     </div>
   </html>
  </iframe>
</html>

Please, considere that angularjs, jquery if applicable, modules-declaration as well as headers are loaded properly.

I'd like to load the html content from main-frame/window into iframe and run interceptors and directives properly. Is it possible? If yes, how can I do it?

Thanks for advancing!

回答1:

I've tried this code and it seems work fine! I found it here: http://www.snip2code.com/Snippet/50430/Angular-Bootstrap

var $rootElement = angular.element(document.getElementById("frame").contentWindow.document);
var modules = [
  'ng',
  'module2',
  function($provide) {
    $provide.value('$rootElement', $rootElement)
  }
];

var $injector = angular.injector(modules);

var $compile = $injector.get('$compile');

$rootElement.find("div#divId").append(scope.content);

var compositeLinkFn = $compile($rootElement);

var $rootScope = $injector.get('$rootScope');
compositeLinkFn($rootScope);

$rootScope.$apply();