AngularJS $sce only html safe a[href]

1.2k views Asked by At

I have a comment textbox and I want only to allow a[href] as safe html with ngSanitize/$sce. So I'm trying this:

<span contact-highlight hightlight-value="showedText" ng-bind-html="showedText"></span>

And inside my contactHiglight directive I have this:

contentObjectApp.directive('contactHighlight', function ($sce) {
    return {
        restrict: 'A',
        scope: { hightlightValue: '=' },
        link: function ($scope, $element, $attrs) {
            $scope.hightlightValue = "<h2> testing" + $sce.trustAsHtml('<a href="#">render me please</a>') + " </h2>";
        }
     };
});

I ways expecting to only allow the 'render me please' to become a href link but I always expecting to be rendered as well. What am I missing? Is there an easy way to do this?

1

There are 1 answers

0
MatFiz On

According to the docs of the Angular 1.3.7 (https://docs.angularjs.org/api/ng/service/$sce), if you want to pass just links, use $sce.trustAs($sce.URL, value_to_parse).

I recommend you to use a filter:

angular.module('App', [])
.filter('asHtml', function($sce) {
  return function(input) {
    return $sce.trustAs($sce.URL, input);
  };
})

Then in your view you can use it as:

<span ng-bind-html="value_to_parse | asHtml"> </span>