【问题标题】:angularjs to output html clickable element instead of html as a stringangularjs输出html可点击元素而不是html作为字符串
【发布时间】:2015-08-18 09:08:06
【问题描述】:

我正在使用过滤器从一段内容中转换任何 URL 或电子邮件 ID。但它被呈现为字符串而不是可点击的 HTML 元素。

过滤 JS

angular.module('myApp.filters', []).filter('parseUrl', function() {
    var urls = /(\b(https?|ftp):\/\/[A-Z0-9+&@#\/%?=~_|!:,.;-]*[-A-Z0-9+&@#\/%=~_|])/gim
    var emails = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim

    return function(text) {

        if (text.match(urls)) {
            text = text.replace(urls, "<a href=\"$1\" target=\"_blank\">$1</a>")
        }
        if (text.match(emails)) {
            text = text.replace(emails, "<a href=\"mailto:$1\">$1</a>")
        }

        return text
    }
});

上面的代码给我输出了一个平面文本而不是可点击的 HTML 元素。

Fiddle

【问题讨论】:

标签: angularjs angularjs-filter


【解决方案1】:

我已经更新JS Fidle

HTML: 添加了

ng-bind-html

<div ng-app="miniapp">
    <div ng-controller="Ctrl">
         <h1 ng-bind-html="test | parseUrl">{{test}}</h1>
    </div>
</div>

Documentation ngBindHtml

【讨论】:

    【解决方案2】:

    您的过滤器应该使用严格的上下文转义$sce 来返回受信任的 HTML

    angular.module('myApp.filters', []).filter('parseUrl', function ($sce) {
         var urls = /(\b(https?|ftp):\/\/[A-Z0-9+&@#\/%?=~_|!:,.;-]*[-A-Z0-9+&@#\/%=~_|])/gim
         var emails = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim
    
         return function (text) {
             if (text.match(urls)) {
                 text = text.replace(urls, "<a ng-href=\"$1\" target=\"_blank\">$1</a>");
             }
    
             if (text.match(emails)) {
                 text = text.replace(emails, "<a ng-href=\"mailto:$1\">$1</a>");
             }
    
             return $sce.trustAsHtml(text);
         }
     });
    

    更新

    看来您使用的是旧版本的 Angular(版本 1.0.2),它没有严格的上下文转义 $sce。这解释了您对ngSanitize 模块的使用。

    您的过滤器代码是正确的,但您应该使用 ng-bind-html 以不同方式绑定您的文本。

    <div ng-app="miniapp">
        <div ng-controller="Ctrl">
             <h1 ng-bind-html="test | parseUrl"></h1>
        </div>
    </div>
    

    JsFiddle : http://jsfiddle.net/fb4meygo/1/

    【讨论】:

    • 检查我的问题,我在我的问题中添加了小提琴。我在本地尝试了您的解决方案。但没有运气......
    【解决方案3】:

    在链接过滤器的帮助下,我们可以从文本中检测链接并以不同的方式显示它们。 Linky 通过将所有 URL 包装到锚标记中来获取文本并生成 HTML。支持邮箱地址、http、https、mailto。

    HTML:

    <div ng-app="myApp" ng-controller="myController">
        <div>
            <p ng-bind-html="myText | linky :'_blank'"></p>
            <textarea ng-model="myText" style="width: 420px; height: 120px"></textarea>
        </div>
    </div>
    

    控制器:

    var myApp = angular.module('myApp', ['ngSanitize'])
    .controller('myController', ['$scope', function ($scope) {
        $scope.myText = "Some default text is here http:/tothenew.com/";
    }]);
    

    【讨论】:

      猜你喜欢
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 2020-05-23
      • 2013-06-21
      • 2019-10-16
      • 1970-01-01
      相关资源
      最近更新 更多