0

嗨,我是Angualr JS的新手,如果它包含帶有標籤的單詞,然後將該單詞作爲鏈接,我想過濾每個返回的Twitter文本。如何製作自定義Angular過濾器

返回Twitter文字是 「敏捷的棕色#fox躍過懶#dog」然後使返回的文本 「敏捷的棕色<a href="page.link">#fox</a>跳通過惰性<a href="page.link">#dog</a>

HTML代碼

<ul class="list-unstyled"> 
    <li ng-repeat="tweet in tweets" class="striped"> 
     <p ng-bind-html="tweet.text | filter:hashtag"></p> 
    </li> 
</ul> 

JS代碼

app.filter('hashtag', function(){ 


}); 
+0

你有什麼試過,這是行不通的?首先你需要的是匹配標籤的方式,像'/#\ w +/g'應該讓你開始。具體來說,你需要像'tweetText.replace(/#\ w +/g,'$&')' – Phil

+0

它的工作原理,謝謝@Phil – PenAndPapers

+0

Pff!當我發佈我的答案時,我沒有注意到@菲爾的評論。他的評論圍繞着我的答案響起。 – developer033

回答

0

首先,使用filter,你應該只調用是這樣的:

<p ng-bind-html="tweet.text | hashtag"></p> 

然後,讓你的過濾工作,你可以做這樣的事情:

(function() { 
 
    "use strict"; 
 

 
    angular 
 
    .module('app', ['ngSanitize']) 
 
    .controller('MainCtrl', MainCtrl) 
 
    .filter('hashtag', hashtag); 
 

 
    MainCtrl.$inject = ['$scope']; 
 

 
    function MainCtrl($scope) { 
 
    $scope.tweets = []; 
 

 
    for (var i = 0; i < 10; i++) { 
 
     $scope.tweets.push({ 
 
     "text": "A text with hashtag #ex " + i + " another #ex " + (i + 1) 
 
     }) 
 
    } 
 
    } 
 

 
    function hashtag() { 
 
    return function(input) { 
 
     if (!input) return; 
 

 
     var regex = new RegExp('(#[^ ]*)', 'g'); 
 
     var matches = []; 
 
     var match; 
 
     while (match = regex.exec(input)) { 
 
     matches.push(match[0]); 
 
     } 
 

 
     matches.forEach(function(match) { 
 
     input = input.replace(new RegExp('(' + match + ')', 'g'), '<a href="page.link">$1</a>') 
 
     }); 
 

 
     return input; 
 
    }; 
 
    } 
 
})();
<!DOCTYPE html> 
 
<html ng-app="app"> 
 

 
<head> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular-sanitize.min.js"></script> 
 
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" /> 
 
</head> 
 

 
<body ng-controller="MainCtrl"> 
 
    <ul class="list-unstyled"> 
 
    <li ng-repeat="tweet in tweets" class="striped"> 
 
     <p ng-bind-html="tweet.text | hashtag"></p> 
 
    </li> 
 
    </ul> 
 
</body> 
 

 
</html>

相關問題