Javascript 通过文本搜索和下拉菜单进行角度过滤

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32218231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:46:03  来源:igfitidea点击:

Angular filter by text search and dropdown

javascriptangularjsangularjs-ng-repeatangular-filters

提问by jminterwebs

I'm having trouble and I can't seem to find an answer. I'm trying to filter using an text input box and a drop down menu. Its for a fantasy football app to give you an idea. Some code below

我遇到了麻烦,我似乎无法找到答案。我正在尝试使用文本输入框和下拉菜单进行过滤。它是一个梦幻足球应用程序,可以给你一个想法。下面的一些代码

 <form class="form-inline search-width">
<input class="search form-control" type="text" ng-model="nameSearch.name">
<select class="form-control" ng-model="nameSearch.position">
    <option value="All">All</option>
    <option value="QB">QB</option>
    <option value="RB">RB</option>
    <option value="WR">WR</option>
    <option value="TE">TE</option>
    <option value="DEF">DEF</option>
    <option value="K">K</option>
</select>
    {{nameSearch.position}}
</form>
<ul class="list">

    <li ng-repeat="list in playerlist" 
        ng-click="PlayerSelected($event, this)">Rank: {{list.Rank}} Pos: {{list.Position}} {{list.Team}}</br>
        {{list.Last}}, {{list.First}} Bye: {{list.Bye}}</li>

</ul>

I have the faintest idea of how to make the search work with both inputs. The drop down should only search the position value. The input box can really seach anything.

我对如何使搜索与两个输入一起工作一无所知。下拉菜单应该只搜索位置值。输入框真的可以搜索到任何东西。

采纳答案by Dmitry Bogomolov

Custom filter can be useful in your situation. That how I would solve this.

自定义过滤器在您的情况下很有用。那我将如何解决这个问题。

The filter:

过滤器:

angular.module('DraftBoard').filter('playersFilter', function () {
    return function (input, filterObject) {
        if (filterObject == undefined) { return input; }

        var searchName = filterObject.name.toLowerCase();
        var searchPosition = filterObject.position.toLowerCase();
        var out = [];
        if (input != undefined) {
            for (var i = 0; i < input.length; i++) {

                var firstName = input[i].First != undefined ? input[i].First.toString().toLowerCase() : '';
                var lastName = input[i].Last != undefined ? input[i].Last.toString().toLowerCase() : '';
                var team = input[i].Team != undefined ? input[i].Team.toString().toLowerCase() : '';
                var position = input[i].Position != undefined ? input[i].Position.toString().toLowerCase() : '';

                var filterCondition = ((searchPosition === 'all') || (position.indexOf(searchPosition) > -1))
                    && ((searchName == '') || (firstName.indexOf(searchName) > -1) || (lastName.indexOf(searchName) > -1) || (team.indexOf(searchName) > -1));

                if (filterCondition) {
                    out.push(input[i]);
                }
            }
        }
        return out;
    };
});

In your controller add this:

在您的控制器中添加:

$scope.nameSearch = {
        name: '',
        position: 'All'
    };

And in the view use it this way:

并在视图中以这种方式使用它:

<div class="selectionlist">
    <form class="form-inline search-width">
    <input class="search form-control" type="text" ng-model="nameSearch.name">
    <select class="form-control" ng-model="nameSearch.position">
        <option value="All">All</option>
        <option value="QB">QB</option>
        <option value="RB">RB</option>
        <option value="WR">WR</option>
        <option value="TE">TE</option>
        <option value="DEF">DEF</option>
        <option value="K">K</option>
    </select>
        {{nameSearch.position}}
    </form>
    <ul class="list">

        <li ng-repeat="list in playerlist | playersFilter:nameSearch "
            ng-click="PlayerSelected($event, this)">
            Rank: {{list.Rank}} Pos: {{list.Position}} {{list.Team}}</br>
            {{list.Last}}, {{list.First}} Bye: {{list.Bye}}
        </li>

    </ul>

</div>

回答by gm2008

ui.bootstrap.typeahead plugin may be what you need:

ui.bootstrap.typeahead 插件可能就是你所需要的:

http://angular-ui.github.io/bootstrap/

http://angular-ui.github.io/bootstrap/

Screenshot: https://i.stack.imgur.com/VJenP.png

截图:https: //i.stack.imgur.com/VJenP.png

It adds an uib-typeaheadattribute to the <input> tag.

uib-typeahead向 <input> 标签添加了一个属性。

A usage example:

一个使用示例

<input type="text" ng-model="customPopupSelected" 
    placeholder="Custom popup template" 
    uib-typeahead="state as state.name for state in statesWithFlags | filter:{name:$viewValue}" 
    typeahead-popup-template-url="customPopupTemplate.html" 
    class="form-control">

Quotes from its documentation:

引用其文档:

Typeahead is a AngularJS version of Bootstrap v2's typeahead plugin. This directive can be used to quickly create elegant typeaheads with any form text input.

It is very well integrated into AngularJS as it uses a subset of the select directive syntax, which is very flexible. Supported expressions are:

label for value in sourceArray select as label for value in sourceArray The sourceArray expression can use a special $viewValue variable that >corresponds to the value entered inside the input.

This directive works with promises, meaning you can retrieve matches using the >$http service with minimal effort.

Typeahead 是 Bootstrap v2 的 typeahead 插件的 AngularJS 版本。该指令可用于使用任何表单文本输入快速创建优雅的预先输入。

它很好地集成到 AngularJS 中,因为它使用了 select 指令语法的一个子集,非常灵活。支持的表达式有:

sourceArray 中值的标签 选择作为 sourceArray 中值的标签 sourceArray 表达式可以使用一个特殊的 $viewValue 变量,该变量 > 对应于输入中输入的值。

该指令与承诺一起使用,这意味着您可以使用 >$http 服务轻松检索匹配项。

回答by Alejandro Garcia Anglada

You should use the filter option from ng-repeat, here is an examplefor you to check, I hope this help you.

您应该使用 ng-repeat 中的过滤器选项,这里有一个示例供您检查,希望对您有所帮助。

回答by Venkata Krishna

Change your <select>'s ng-modelto nameSearch.Position(uppercase P) so that it matches the position field name of playerlist

将您的<select>'s更改ng-modelnameSearch.Position(大写 P),使其与玩家列表的位置字段名称匹配

   <select class="form-control" ng-model="nameSearch.Position">

Then change your ng-repeat second filter to nameSearchinstead of nameSearch.position.

然后将您的 ng-repeat 第二个过滤器更改为nameSearch而不是nameSearch.position.

 ng-repeat="list in playerlist | filter:searchname | filter: nameSearch"

If you have search inputs with the same name as the object's attributes(eg:nameSearch.Positionsame as playerlist.Position), filtering just by the filter object(nameSearch) without the filter attribute(Position) will search mapping the respective attributes with same name.

如果您有与对象属性同名的搜索输入(例如:nameSearch.Positionsame as playerlist.Position),仅通过过滤器对象(nameSearch)过滤而没有过滤器属性(Position)将搜索映射具有相同名称的各个属性。

UPDATE:The above will help you getting the Position dropdown search fixed.
For the name, use a custom filter as below.
Please note searchnameis added as a filter in ng-repeatand keep your search input's ng-modela non object. For the below controller you would have to keep it as
<input class="search form-control" type="text" ng-model="nameSearch">

更新:以上将帮助您修复位置下拉搜索。
对于名称,请使用如下自定义过滤器。
请注意searchname作为过滤器添加ng-repeat并保持您的搜索输入的ng-model非对象。对于以下控制器,您必须将其保留为
<input class="search form-control" type="text" ng-model="nameSearch">

Controller:

控制器:

$scope.searchname = function (row) {
        return (angular.lowercase(row.First).indexOf($scope.nameSearch || '') !== -1 || angular.lowercase(row.Last).indexOf($scope.nameSearch || '') !== -1);
    };

Hope this helped.

希望这有帮助。

回答by Shasha

Here u can find custom filter for dropdown and search

在这里您可以找到用于下拉和搜索的自定义过滤器

i hope this Codewill help with something new way !

我希望这个代码能以新的方式帮助你!

回答by Ronnie

here is my crack at this http://jsfiddle.net/0ey84dwu/

这是我的裂缝 http://jsfiddle.net/0ey84dwu/

HTML: Use ng-repeatand filter it by the text input. Also, use ng-options

HTML:ng-repeat通过文本输入使用和过滤它。另外,使用ng-options

    <div ng-app="TestApp">
        <div ng-controller="TestController">
            <input class="search form-control" type="text" ng-model="nameSearch.name">
            <select class="form-control" ng-options="position as position for position in positions" ng-model="nameSearch.position" ng-change="setPosition()">
            </select>

            <div ng-repeat="player in players | filter: nameSearch.name">
               {{player.First}} {{player.Last}}
            </div>
        </div>
    </div>

And then the JS: Have an array of all the players. Depending on your selection of the dropdown, add those players to a new array that contain only players of the selected position. Selecting Allwill set $scope.players = $scope.allPlayersthus filtering all players by whatever you are searching.

然后是 JS:拥有所有玩家的数组。根据您对下拉列表的选择,将这些球员添加到仅包含所选位置的球员的新数组中。选择All将设置,$scope.players = $scope.allPlayers从而根据您正在搜索的内容过滤所有玩家。

var app = angular.module('TestApp',[]);

app.controller('TestController', function($scope)
{
  $scope.nameSearch = {};
  $scope.nameSearch.position = 'All';
  $scope.positions = ['All','QB','RB','WR','TE','DEF','K'];
  $scope.players = $scope.allPlayers;

  $scope.setPosition = function()
  {
    $scope.players = [];
    if ($scope.nameSearch.position != 'All')
    {
       for (var i in $scope.allPlayers) if ($scope.allPlayers[i].Position == $scope.nameSearch.position) $scope.players.push($scope.allPlayers[i]);   
       return;
     }
     $scope.players = $scope.allPlayers;
  };

  $scope.allPlayers = [
  {
    "Rank":1,
    "First":"Le'Veon",
    "Last":"Bell",
    "Position":"RB",
    "Team":"PIT",
    "Bye Week":11
  },
  {
    "Rank":2,
    "First":"Jamaal",
    "Last":"Charles",
    "Position":"RB",
    "Team":"KC",
    "Bye Week":9
  },
  {
    "Rank":3,
    "First":"Adrian",
    "Last":"Peterson",
    "Position":"RB",
    "Team":"MIN",
    "Bye Week":5
  }...
  ...
  ..
  ...];

  $scope.setPosition();

});

You could write a custom filter and shorten this code even more

您可以编写自定义过滤器并进一步缩短此代码