【问题标题】:How to make custom Angular filter如何制作自定义角度过滤器
【发布时间】:2016-12-11 06:38:17
【问题描述】:

您好,我是 Angualr JS 的新手,我想过滤每个返回的 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(){


});

【问题讨论】:

  • 您尝试过哪些不起作用的方法?您需要的第一件事是匹配主题标签的方法,例如/#\w+/g 应该可以帮助您入门。具体来说,你会想要tweetText.replace(/#\w+/g, '&lt;a href="page.link"&gt;$&amp;&lt;/a&gt;')
  • 它有效,谢谢@Phil
  • 噗!当我发布我的答案时,我没有注意到@Phil 的评论。他的评论围绕着我的答案。
  • 不用担心@developer033,现在有了你的代码我知道在制作自定义过滤器时我不需要在指令中添加 filter: 只是自定义过滤器的名称谢谢.

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


【解决方案1】:

首先,要使用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>

【讨论】:

    猜你喜欢
    • 2020-07-27
    • 2019-02-16
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 2021-09-09
    相关资源
    最近更新 更多