AngularJS $ sce只有html安全a [href]

时间:2023-01-13 19:42:38

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

我有一个评论文本框,我只想允许[href]作为安全的HTML与ngSanitize / $ sce。所以我正在尝试这个:

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

And inside my contactHiglight directive I have this:

在我的contactHiglight指令中,我有这个:

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?

我希望只允许'渲染我'成为一个href链接,但我总是希望能够渲染。我错过了什么?是否有捷径可寻?

1 个解决方案

#1


2  

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

根据Angular 1.3.7(https://docs.angularjs.org/api/ng/service/$sce)的文档,如果你想传递链接,请使用$ 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>

#1


2  

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

根据Angular 1.3.7(https://docs.angularjs.org/api/ng/service/$sce)的文档,如果你想传递链接,请使用$ 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>