【问题标题】:How to call one filter from another filter in angular.js如何从 angular.js 中的另一个过滤器调用一个过滤器
【发布时间】:2013-12-21 05:16:59
【问题描述】:

我有一个过滤器 linkifyStuff,我希望在其中使用另一个过滤器处理一些变量。我无法弄清楚从另一个过滤器调用一个过滤器的语法。

我知道过滤器链接——这不是我想做的。我想将过滤器应用于 linkifyStuff 过滤器中的局部变量,而不是应用于其输入或输出。

我希望以下内容可以正常工作,但 $filter('filtername') 显然不是正确的语法。

module.filter('sanitizeStuff', function() {
    // ...
})

module.filter('prettifyStuff', function() {
    // ...
})

module.filter('linkifyStuff', function($filter) {
    return function(text) {
        // ...
        // ...
        return $filter('sanitizeStuff')(foo) + ' whatever ' + $filter('prettifyStuff')(bar)
    }
})

我可以为 sanitizeStuff 和 sanitizeStuff 编写一个普通的 js 函数,并从这些过滤器中调用该函数,但这似乎是错误的。关于如何以角度方式进行操作的任何建议?

谢谢。

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    使用<filterName>Filter 语法将您的过滤器注入linkifyStuff。像这样:

    app.filter('linkifyStuff', function(sanitizeStuffFilter,prettifyStuffFilter) {
        return function(text) {
    
            return sanitizeStuffFilter(text) + ' whatever ' + prettifyStuffFilter(text);
        }
    });
    

    DEMO

    【讨论】:

    • 谢谢,正是我需要的!
    • 太好了,谢谢!这就是您可以指定注入另一个过滤器(CoffeeScript)的过滤器的方式:gist.github.com/henrik/06122aedab2f2eace527
    • 有没有办法为默认过滤器做到这一点?,即日期
    • @useless:我不确定角度是否允许,但应该是可能的。在这方面,自定义过滤器和内置过滤器之间应该没有区别。如果它不适合您,您可以尝试:$filter('date')
    • 不,它不起作用,这就是我提到这个的原因。关于使用 $filter,我在另一个过滤器的定义中,我没有(没有,现在我有)应用程序或 $filter 依赖项的引用。
    【解决方案2】:

    我之前在过滤评论输入时遇到过类似的情况。我有 4 个不同的过滤器,当用户单击提交时,它将运行一个函数,该函数将在评论副本上运行所有 4 个过滤器。把我的过滤器扔在那里以防万一。警告:确保将 $filter 注入控制器,我讨厌忘记注入东西。这是代码:

    注入:

    .controller('Controller', function ($scope, $filter){
        //CODE GOES HERE
    });
    

    HTML:

    <ul ng-repeat="comment in comments">
        <li>{{comment.user_name}}</li>
        <li dynamic="deliberatelyTrustDangerousSnippet(comment.comment_copy)"></li>
    </ul>
    

    控制器:

    $scope.deliberatelyTrustDangerousSnippet = function(comment) {
        comment = $filter('breaks')(comment);
        comment = $filter('links')(comment);
        comment = $filter('images')(comment);
        comment = $filter('youtubeLinks')(comment);
        return comment;
    
    };
    

    过滤器:

    .filter('breaks', function () {
        return function (text) {
            if (text !== undefined) return text.replace(/&#10;/g, '<br />');
        };
    })
    .filter('links', function () {
        return function (text) {
            if (text !== undefined){
                return text.replace(/(?:http:\/\/)?(?:www\.)?((?:[\w-\.]*)(?:\.(?:com|net|org|co|be))(?:(?:[\/?\w?=?&?(?:&amp;)?\.?-]*)))/g, '<a target="_blank" href="http://$1">$1</a>');
            }
        };
    })
    .filter('images', function () {
        return function (text) {
            if (text !== undefined){
                return text.replace(/(?:<.*=")(.*(?:(?:\.(?:jpg|JPG|png|PNG|gif|GIF|jpeg|JPEG))))(?:")(?:.*(?:<\/a>))/g, '<img src="$1"/>');
            }
        };
    })
    .filter('youtubeLinks', function () {
        return function (text) {
            if (text !== undefined){
                return text.replace(/(?:<.*=")(?:(?:(?:(?:http:\/\/)|(?:www\.)|(?:http:\/\/www\.))(?:(?:youtube\.com.*v=)|(?:youtu\.be\/))((?:\w|\d|-)*)(?:(?:&amp;feature=related)?)))(?:")(?:.*(?:<\/a>))/g, '<youtube id="$1"></youtube>');
            }
        };
    })
    

    【讨论】:

      【解决方案3】:

      @useless 询问“是否有任何方法可以对默认过滤器执行此操作。”

      使用默认过滤器的一种迂回方式:通过标准过滤器将其传递给自定义过滤器,然后将原始值作为参数传递。

      例如,您的 Angular 表达式如下所示:

      {{myDate | date: 'mediumDate' | relativeDate: myDate}}
      

      还有你的过滤器:

      var myApp = angular.module('myApp',[]);
      myApp
          .filter('relativeDate', function() {
              return function(formattedDate, dateStr) {
                  var returnVal = formattedDate,
                      today = new Date(),
                      evalDate = new Date(dateStr);
                  if (today.getFullYear() == evalDate.getFullYear() &&
                      today.getMonth() == evalDate.getMonth() &&
                      today.getDate() == evalDate.getDate()) {
                          returnVal = 'Today'
                  }
                  return returnVal
              }
          })
          .controller('myAppCtrl', ['$scope', function myAppCntrl($scope) {
              $scope.myDate = "2001-01-01T01:01:01";
          });
      

      【讨论】:

        【解决方案4】:
        app.filter('linkifyStuff', function(sanitizeStuffFilter,prettifyStuffFilter) {
            return function(text) {
        
                return sanitizeStuffFilter(text) + ' whatever ' + prettifyStuffFilter(text);
            }
        });
        

        这不适合我。如果有人对上述代码有问题。你可以试试这个,对我来说效果很好。

        app.filter('linkifyStuff', function($filter) {
                return function(text) {
        
                    return $filter('sanitizeStuffFilter')(text) + ' whatever ' + $filter('prettifyStuffFilter')(text);
                }
            });
        

        【讨论】:

        • 谢谢。我对第一个建议也有问题,但最后一个代码也为我解决了问题。
        【解决方案5】:

        最新方式示例:

        angular.module('myApp.shared.shared-filters', [])
        .filter('capitalize', ['$filter', function($filter) {
          return function(input) {
            return $filter('uppercase')(input.charAt(0)) + $filter('lowercase')(input.substr(1));
          }
        }]);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-08-19
          • 1970-01-01
          • 1970-01-01
          • 2021-03-17
          • 1970-01-01
          • 1970-01-01
          • 2021-09-07
          • 2016-08-16
          相关资源
          最近更新 更多