2016-11-22 30 views
0

我有包含鏈接的字符串,我想使鏈接可點擊。在角度上我將如何去做這件事。如何在angularjs中的字符串中創建鏈接標記?

這裏是JSON數據串的一個例子,我有「我的託管#AFF時裝秀@Bullring於9月27日與@BillieFaiers。點擊這裏瞭解更多> http://www.clickhereformoreinfo.com

基本上我想要的哈希標籤,符號和鏈接都是標籤。現在請幫忙​​一直努力。

+0

您將使用簡單的JavaScript函數。找到一個正則表達式來捕獲鏈接,哈希字符和@。然後使用結果將其替換爲帶有href內部鏈接的'a'標籤。嘗試一些然後回來的問題/錯誤 – Weedoze

+0

可能重複的[防止Angular轉義HTML](http://stackoverflow.com/questions/20778709/prevent-angular-from-escaping-html) – BetaRide

+0

重複的http:// stackoverflow.com/questions/21475837/angularjs-create-html-link-anchor-from-text-escape-unescape-html-in-view – ggilberth

回答

0

試試這個:

查看

<div ng-repeat="text in texts"> 
    <p ng-bind-html="text | parseUrl"></p> 
</div> 

指令

angular.module('filters', []) 
    .filter('parseUrl', function() { 
     var urls = /(\b(https?|ftp):\/\/[A-Z0-9+&@#\/%?=~_|!:,.;-]*[-A-Z0-9+&@#\/%=~_|])/gim 
     var emails = /(\[email protected][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 
     } 
    }); 

https://plnkr.co/edit/k4vL5yeHHyLqYu7el7b5?p=preview

+0

什麼是「comment.body」代表?我從ng-repeat中加載這些數據。我將如何從中獲取字符串? –

+0

看看這個:https://plnkr.co/edit/k4vL5yeHHyLqYu7el7b5?p=preview – KungWaz

+0

然後請標記爲接受的答案 – KungWaz

0

試試這個:

var myApp = angular.module('myApp',[]); 
 

 
myApp.controller('MyCtrl',function($scope) { 
 
    var str = "I’m hosting #AFF Catwalk Show @Bullring on 27th Sept with @BillieFaiers. Find out more here > http://www.clickhereformoreinfo.com"; 
 
    var subStr = str.split(">"); 
 
    $scope.name = subStr[0]; 
 
    $scope.link = subStr[1]; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="MyCtrl"> 
 
    {{name}}<a href="link">{{link}}</a> 
 
</div>

相關問題