Angular - 通过不同的框架附加 html,每帧一个模块

2023-12-08

我的代码有主窗口和一个 iframe,每个 iframe 都有您的模块。主窗口中的按钮触发单击事件,该事件应将 html 附加到 iframe 中,新的 html 附加到该事件中时应正确应用拦截器和指令,但它不起作用! 角度 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 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>

请考虑 angularjs、jquery(如果适用)、模块声明以及标头是否已正确加载。

我想将 html 内容从 main-frame/window 加载到 iframe 中并正确运行拦截器和指令。是否可以?如果是,我该怎么做?

感谢您的进步!


我已经尝试过这段代码,它似乎工作正常!我在这里找到了它: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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular - 通过不同的框架附加 html,每帧一个模块 的相关文章

随机推荐