小编典典

角度ng-bind-html和其中的指令

angularjs

plnkr链接

我有一个我想将html绑定到它的元素。

<div ng-bind-html="details" upper></div>

这样可行。现在,连同它,我还有一个绑定到绑定的html的指令:

$scope.details = 'Success! <a href="#/details/12" upper>details</a>'

但是upper带有div和anchor 的指令不求值。我该如何运作?


阅读 281

收藏
2020-07-04

共1个答案

小编典典

我也遇到了这个问题,经过几个小时的互联网搜索,我读到了@Chandermani的评论,事实证明这是解决方案。您需要使用以下模式调用“编译”指令:

HTML:

<div compile="details"></div>

JS:

.directive('compile', ['$compile', function ($compile) {
    return function(scope, element, attrs) {
        scope.$watch(
            function(scope) {
                // watch the 'compile' expression for changes
                return scope.$eval(attrs.compile);
            },
            function(value) {
                // when the 'compile' expression changes
                // assign it into the current DOM
                element.html(value);

                // compile the new DOM and link it to the current
                // scope.
                // NOTE: we only compile .childNodes so that
                // we don't get into infinite loop compiling ourselves
                $compile(element.contents())(scope);
            }
        );
    };
}])

您可以在这里看到它的工作提琴

2020-07-04