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

标签 html angularjs iframe

我的代码有主 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(如果适用)、模块声明和 header 。

我想将 html 内容从主框架/窗口加载到 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();

关于html - Angular - 通过不同的框架附加 html,每个框架一个模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23871919/

相关文章:

javascript - 使用 javascript 用户名/密码提示下载

css - 你如何在 Angular-UI-Bootstrap 中缩放轮播容器的大小

iframe - 有没有其他方法可以使用Google Analytics(分析)事件跟踪来跟踪YouTube的API PlayerStateChange?

javascript - 嵌入谷歌地图

python - 如何使用 Selenium 和 Python 3 查找 iframe

html - 彼此相邻的 div 与彼此顶部的嵌套 div?

javascript - 在 HTML 文档中全局禁用拼写检查和自动完成功能?

html - anchor 标签div名称

javascript - 如何从 angularjs 中的 JSON 数组动态生成列标题和表值?

javascript - 使用 Angular JS 将父 div 的焦点更改为子 href 元素的焦点