0
votes

Hi I'm new to Angualr JS and I want to filter every returned twitter text if it contains a word with hashtag then make that word a link.

e.g

returned twitter text is "The quick brown #fox jumps over the lazy #dog" then make the returned text as "The quick brown <a href="page.link">#fox</a> jumps over the lazy <a href="page.link">#dog</a>

HTML Code

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

JS code

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


});
1
What have you tried that isn't working? First thing you'll need is a way to match the hashtags, something like /#\w+/g should get you started. Specifically, you'll want something like tweetText.replace(/#\w+/g, '<a href="page.link">$&</a>') - Phil
it works, thanks @Phil - PenAndPapers
Pff! While I was posting my answer I didn't notice @Phil's comment. His comment run rings around mine answer. - developer033
no worries @developer033, with youre code now I understand that in making custom filter I dont need to add the filter: inside the directive just the name of the custom filter thanks. - PenAndPapers

1 Answers

0
votes

At first, to use a filter you should call only like this:

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

Then, to make your filter work you could do something like this:

(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>