Render AngularJS directive on $http loaded content

坚强是说给别人听的谎言 提交于 2019-12-04 23:26:54
fghibellini

an almost correct asnwer can be found at angular ng-bind-html 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);
             });
        }   
    };  
});

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:

  • you are completely violating the idea of mvc
  • by restricting the elements with directives you're basicaly blacklisting elements which is generaly not a good idea you should use a whitelist.
  • It is also very insecure to allow user input be part of your angular running context.

it would be a better idea to filter the input html through a whitelist function and then bind that with ng-bind-html.

Angular is using 'a' as a directive as priority '0' (https://docs.angularjs.org/api/ng/directive/a)

Try doing this:

  • set your priority higher than what was defined, example 1 or Number.MAX_VALUE.
  • set terminal to true, so it won't process the lower priorities.

could work, i guess... :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!