在$http加载的内容上呈现AngularJS指令

Render AngularJS directive on $http loaded content

本文关键字:AngularJS 指令 http 加载      更新时间:2023-09-26

我有点问题。我有指令

app.directive('a', function() {
    return {
        restrict: 'E',
        link: function(scope, elem, attrs) {
            elem.on('click', function(e){
                e.preventDefault();
                alert('Hyperlinks not allowed!');
            });
        }
    };
});

以及针对包含页面内容的CCD_ 2的$http请求

{
    "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>

现在的问题是:如何实现加载内容的<a>标记作为指令工作

谢谢。

在angular ng-bind-html和其中的指令中可以找到一个几乎正确的asnwer,尽管更好的形式是:

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-bind-html只需将数据分配给html,而不在其上运行$compile(请参阅https://github.com/angular/angular.js/blob/master/src/ng/directive/ngBind.js#L197)。这仍然不是完全正确的,因为当值发生变化时,所包含的指令没有被通知它们正在被销毁,因此会有更好的版本

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);
            });
        }
    };
});

从角度来看,这是正确的,但是:

  • 你完全违反了mvc的理念
  • 通过用指令限制元素,你基本上将元素列入黑名单,这通常不是一个好主意,你应该使用白名单
  • 允许用户输入成为有角度的运行上下文的一部分也是非常不安全的

最好是通过白名单函数过滤输入的html,然后将其与ng-bind-html绑定。

Angular正在使用"a"作为优先级为"0"的指令(https://docs.angularjs.org/api/ng/directive/a)

尝试这样做:

  • 将优先级设置为高于定义的优先级,例如1或Number.MAX_VALUE
  • 将terminal设置为true,这样它就不会处理较低的优先级

可以工作,我想…:)