渲染上$ HTTP加载的内容AngularJS指令 [英] Render AngularJS directive on $http loaded content
问题描述
我有一个有点问题。我有一个指令
I have a bit of a problem. I have a directive
app.directive('a', function() {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
elem.on('click', function(e){
e.preventDefault();
alert('Hyperlinks not allowed!');
});
}
};
});
和包含的页面内容 JSON
A $ HTTP
要求
and a $http
request for JSON
containing the page content
{
"currentNodeName":"Page 1",
"childrenNodes":[
{"id":"3","name":"Page 1-1"},
{"id":"4","name":"Page 1-2"}],
"parentNode":null,
"currentNodeContent":[
{"content":"<p>This is Page1. <a href=\"http://badlink.org/i/dont/want/to/work\">Link</a></p>"}],
"currentNodeId":"1"
}
的 currentNodeContent
加载到一个 DIV
<div id="loadedContent" ng-bind-html="boardCtrl.nodeData.currentNodeContent[0].content"></div>
和现在的问题:
我如何能够做到这一点所加载内容的&LT; A&GT;
标签可以作为一个指令
and now the question:
How can I achieve that the loaded content's <a>
tag works as a directive?
感谢。
推荐答案
几乎是正确的asnwer可以发现<一个href=\"http://stackoverflow.com/questions/17417607/angular-ng-bind-html-unsafe-and-directive-within-it\">angular NG-绑定HTML的不安全和指令中它的,虽然一个更好的形式是:
an almost correct asnwer can be found at angular ng-bind-html-unsafe and directive within it although a better form would be:
app.directive("unsecureBind", function($compile) {
return {
link: function(scope, element, attrs) {
scope.$watch(attrs.unsecureBind, function(newval) {
element.html(newval);
$compile(element.contents())(scope);
});
}
};
});
在NG-绑定,HTML只是分配数据的HTML不运行$编译就可以了(见的 https://github.com/angular/angular.js/blob/master/src/ng/directive/ngBind.js#L197 )。
这仍然是不完全正确becouse的价值变化所包含的指令不通知,他们被摧毁,因此一个更好的版本会。
The ng-bind-html simply assigns the data to the html without running $compile on it (see https://github.com/angular/angular.js/blob/master/src/ng/directive/ngBind.js#L197 ). This still isn't completely right becouse on change of the value the contained directives are not notified that they are being destroyed a better version would therefore be.
app.directive("unsecureBind", function($compile) {
return {
link: function(scope, element, attrs) {
var childscope;
scope.$watch(attrs.unsecureBind, function(newval, oldval) {
if (!newval && !oldval) return; // handle first run
if (childscope)
childscope.$destroy();
element.html(newval || "");
if (!newval) return;
childscope = scope.$new();
$compile(element.contents())(childscope);
});
}
};
});
这是从视图角点正确的,但是:
This is correct from the angular point of view, BUT:
- 您完全违反了MVC的想法
- 通过限制与指令的元素你basicaly黑名单元素是generaly不应该使用白名单是一个好主意。
- 这也是非常不安全的,允许用户输入的是你的棱角运行环境的一部分。
这将是一个更好的主意,通过白名单功能来过滤输入HTML,然后绑定与NG绑定HTML的。
it would be a better idea to filter the input html through a whitelist function and then bind that with ng-bind-html.
这篇关于渲染上$ HTTP加载的内容AngularJS指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!