Search code examples
javascriptangularjsangularjs-directivefrontendangular-filters

How to make custom Angular filter


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


});

Solution

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