【问题标题】:Angular - append html through different frames with one module per frameAngular - 通过不同的帧附加 html,每帧一个模块
【发布时间】:2014-07-15 07:59:55
【问题描述】:

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

<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 并正确运行拦截器和指令。可能吗?如果是,我该怎么做?

感谢您的进步!

【问题讨论】:

    标签: html angularjs iframe


    【解决方案1】:

    我已经尝试过这段代码,它似乎工作正常!我在这里找到它: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();
    

    【讨论】:

      猜你喜欢
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多