【问题标题】:Angular js custom filter for searching with Startswith then contains for ng-repeat用于使用 Startswith 进行搜索的 Angular js 自定义过滤器,然后包含用于 ng-repeat
【发布时间】:2014-03-27 16:14:43
【问题描述】:

我是角度新手, 在我的应用程序中,我有一个 text box 和一个带有 ng-repeat 的列表

当用户在文本框中键入任何内容时,我正在过滤 使用以下代码根据键入的文本得出结果

<input type=textbox ng-model="TypedText"/>

ng-repeat measure in newSearchResults |filter:TypedText

但 Angular 中的默认过滤器提供包含搜索。 我需要开头和下一个包含的结果。 我尝试编写自定义过滤器,但这些都不起作用。帮助我创建自定义过滤器。

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

您可以创建自己的自定义过滤器,如documentation 所示。

{{ filter_expression | filter : array : expression : comparator}}

您需要在此处提供expression 的功能。

因此,假设您要根据值是否“包含”搜索文本进行过滤。您将在控制器中创建一个函数:

 $scope.customFilter = function(value) {
     // value parameter is the value passed in each ng-repeat
     // In your example, it is the measure variable in "ng-repeat measure in
     // newSearchResults

     if (value.indexOf($scope.TypedText) !== -1) {
         return true;
     } else {
         return false;
     }
 };

如果您在自定义过滤器函数中返回 true,则显示该值,否则不显示。

然后您可以像使用任何其他过滤器一样使用自定义过滤器:

<div ng-repeat="measure in newSearchResults | filter:customFilter()">
    //Repeating tags here
</div>

【讨论】:

  • 在调用过滤器“filter:customFilter()”时不要使用“()”。只需传递名称 'filter:customFilter'
【解决方案2】:

就像第一个答案中提到的那样,您可以将一个函数传递给过滤器,它会为您进行检查。

 $scope.customFilter = function(item) {

     var typedTextLength = ($scope.typedText) ? ($scope.typedText).length : 0,
         substring = (item.yourValueToCheck).substring(0, typedTextLength);

     return ($scope.typedText === substring);

 };

【讨论】:

    猜你喜欢
    • 2013-10-30
    • 2018-03-06
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2017-05-28
    相关资源
    最近更新 更多