简体   繁体   English

针对特定范围将文本编译为有角度的html并将其呈现为DOM

[英]Compiling text into angular html for a specific scope and render it into DOM

I have some specific requirement. 我有一些具体要求。 I have html pages for a functionality (like popup). 我有功能的HTML页面(如弹出窗口)。 I want that html to be rendered while changing my state. 我希望在更改我的状态时呈现该html。 In this, my state specific HTML is different. 在这方面,我特定于状态的HTML是不同的。 Html which I want to render is should get render as a immediate child of body and it contains Angular tag like ng-click etc. 我要渲染的HTML应该作为身体的直接子对象进行渲染,并且它包含ng-click等Angular标签。

I want to load it by calling a function(manually). 我想通过调用一个函数来加载它(手动)。

This worked for me : 这为我工作:

$http.get("/myTemplate.html").then(function(response) {
    var raw_html = response.data;

    $('body').append($compile(raw_html)(myScope));
});

But as per security concern, I can't use $('body').append (jquery apppend) 但是出于安全考虑,我不能使用$('body')。append(jquery apppend)

So I tried it from pure javascript : 所以我尝试从纯javascript:

$http.get("/myTemplate.html").then(function(response) {
    var raw_html = response.data;
    var element = document.createElement("div"); 
    element.className = 'myClass';
    element.innerHTML = raw_html;
    document.body.appendChild($compile(element)(currentScope));
});

But what $compile return is not compatible with appendChild. 但是$ compile返回的内容与appendChild不兼容。

Can directive help me in this case? 在这种情况下,指令可以帮助我吗?

Why don't you use ng-include. 为什么不使用ng-include。

You can use it in 3 different ways: 您可以通过3种不同的方式使用它:

<div ng-include="'/myTemplate.html'"></div>
<div ng-include src='/myTemplate.html'"></div>
<ng-include src="'/myTemplate.html'">

If you must go the other way, you can refer to the dom object by element[0] 如果必须采用其他方法,则可以按element [0]引用dom对象。

Edited 已编辑

document.body.appendChild($compile(element)(currentScope)[0]);

它像本文档一样工作。body.appendChild($ compile(element)(currentScope)[0]);

如果您不能使用jQuery,请改用angular.element主体包装在angular的jqLit​​e中。

angular.element(document.body).append($compile(raw_html)(myScope));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM