[英]Render angular's html from the variable on scope
I'm aware of security implications related to my request, but I need to allow a special super admin group of users an ability to create and evaluate angular html contained within variable on current $scope 我知道与请求有关的安全隐患,但是我需要允许特殊的超级用户组创建和评估当前$ scope变量中包含的Angular html的能力。
Here is an example plunk : 下面是一个例子普拉克 :
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl" ng-init="variable = 3; content = '{{ variable }}'">
<div>
The value of $scope.variable === "{{ variable }}"
</div>
<div>
The value of $scope.content === "{{ content }}"
</div>
<br>
<div>
The value of $scope.content is <b>ng-model</b>'ed via the following textarea:<br>
</div>
<textarea rows="3" ng-model="content"></textarea>
<div style="border: 1px solid black">
Instead of rendering the value of the $scope.content field which is currently equal to "{{ content }}" I need to render compiled and evaluated value which should be equal to "{{ variable }}"
</div>
</body>
</html>
Any suggestions? 有什么建议么?
Thank you in advance! 先感谢您!
You can make a directive that uses the $compile
service to do this for you. 您可以创建一个使用
$compile
服务的指令来为您执行此操作。
Here is what I came up with, and a fork of your Plunkr to show that it works. 这是我想出的,还有您的Plunkr的一个分支,证明它有效。
app.directive('compile', function($compile) {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
var prevScope;
scope.$watch(attrs.compile, function(newVal, oldVal) {
// create a span (an inline element) so we have an actual DOM node to
// set the innerHTML of.
var newElem = document.createElement('span');
newElem.innerHTML = newVal;
// clean up first
if (prevScope) {
prevScope.$destroy();
prevScope = null;
}
// clear out the contents of this element
elem.empty();
// and replace it with the raw (uncompiled) node
elem[0].appendChild(newElem);
// now the node is in the DOM so we can compile it
// but we want to use a try..catch because the user
// might be in the middle of typing a new expression,
// but the syntax right now is not valid so the
// expression parser will throw an error.
try {
// compile the node in the DOM with a child of the existing scope
prevScope = scope.$new();
$compile(newElem)(prevScope);
} catch (e) { /* don't need to do anything here */ }
});
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.