如何制作自定义角度滤镜

时间:2016-08-05 00:02:23

标签: javascript angularjs angularjs-directive frontend angular-filters

您好我是Angualr JS的新手,我希望过滤每个返回的Twitter文本,如果它包含带有主题标签的单词,那么请将该单词作为链接。

e.g

返回twitter文本是 &#34;快速的棕色#fox跳过懒惰的#狗&#34; 然后将返回的文本作为 &#34;快速的棕色<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(){


});

1 个答案:

答案 0 :(得分:0)

首先,要使用public class block { public block() { } public block(int id, int? parentid, string name, decimal value) { this.id = id; this.parentid = parentid; this.name = name; this.value = value; } public int id { get; set; } public int? parentid { get; set; } public string name { get; set; } public decimal value { get; set; } } ,您应该只调用:

filter

然后,为了使你的过滤器工作,你可以做这样的事情:

&#13;
&#13;
<p ng-bind-html="tweet.text | hashtag"></p>
&#13;
(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;
    };
  }
})();
&#13;
&#13;
&#13;