简体   繁体   中英

Passing HTML to a template inside Angular directive

I need the HTML in newValue to work but it seems to just spit out escaped charaters

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

My solution using the answer below:

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

You will have to compile the HTML yourself with the $compile -Service. Do something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM