我的代码有主 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/