在数据绑定AngularJS时如何在<p>标记内打印超链接

时间:2017-07-29 10:09:08

标签: javascript html angularjs

我使用控制器转换<input>标记内的任何网络链接,并将其显示在<p>标记中。我希望它以超链接格式显示链接,如 https://www.w3schools.com很棒,但显示

enter image description here

这是我的代码,

我的HTML

    <div class="col-sm-10 col-sm-offset-1">
    <div class="row" style=" margin-top:70px;">

    <div id='dv1'>
             <form> 

                <input ng-model="comment.txtcomment" id="txtcomment" style='width:500px' >
                <button ng-click="addComment()" style='margin-top:10px;'>Post Comment</button>
             </form> 

            <!--displaying comments-->
            <h4>Comments</h4>
                  <p>{{myText}}</p>

    </div>
    <div></div>

我的控制器

(function(){
    angular.module('StayFit')
    .controller('CommentController',['$scope','$state','$http', function($scope,$state,$http){
        $scope.user=JSON.parse(localStorage['User-Data']) || undefined;
        console.log( $scope.user.data);
        $scope.comment={};

        $scope.addComment=function(){
      var text=$scope.comment.txtcomment;  

      //this code will identify any links  
      var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
      var text1=text.replace(exp, "<a href='$1'>$1</a>");
      var exp2 =/(^|[^\/])(www\.[\S]+(\b|$))/gim;
      var val=text1.replace(exp2, '$1<a target="_blank" href="http://$2">$2</a>');
      $scope.myText=val;

        }//.error(function(error){console.log(error);});
    }])}());



      Tried using ng-binding-html, also doesn't work

1 个答案:

答案 0 :(得分:1)

您显然希望将文字用作HTML而不是文字,因此您需要使用ngBindHtml

请注意SCE也会发挥作用,因此您必须使用$scope.myTextVal = $sce.trustAsHtml(val);之类的内容。