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

时间:2014-04-01 19:30:05

标签: javascript angularjs angularjs-directive

我需要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);
        }
    }
})

1 个答案:

答案 0 :(得分:0)

您必须使用$compile - 服务自行编译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);
    }
  }
})