将 HTML 传递给 Angular 指令中的模板

Passing HTML to a template inside Angular directive

本文关键字:指令 Angular HTML      更新时间:2023-09-26

我需要 newValue 中的 HTML 才能工作,但它似乎只是吐出转义的字符

.directive('ngLookup', function () {
    return {
        restrict: 'A',
        scope : {
            text : '='
        },
        template: '{{newValue}}',
        link: function (scope, elem, attrs) {
            scope.newValue = scope.text.replace(/test/g,'<a href="javascript:;">test</a>');                
        }
    }
})

我的解决方案使用以下答案:

.directive('ngLookup', function ($compile) {
    return {
        restrict: 'EA',
        scope : {
            text : '='
        },
        link: function (scope, elem, attrs) {
            var txt = '<span>'+scope.text.replace(/test/g,'<a href="javascript:;">test</a>')+"</span>";
            var newElement = $compile(txt)(scope);
            elem.replaceWith(newElement);
        }
    }
})

您必须使用 $compile -Service 自己编译 HTML。执行以下操作:

.directive('ngLookup', function ($compile) {
  return {
    restrict: 'A',
    scope : {
        text : '='
    },
    link: function (scope, elem, attrs) {
        var newElement = $compile('<a href="javascript:;">test</a>')(scope);
        elem.replaceWith(newElement);
    }
  }
})