仅在单击按钮时进行角度过滤器

Angular filter only on button click

本文关键字:过滤器 单击 按钮      更新时间:2023-09-26

我似乎无法让我的过滤器只在点击按钮时执行,它第一次执行,然后根据框中的任何文本自动过滤。有人能帮我吗?

<section class="searchField">
        <input type="text" ng-model="searchTerm">
        <button type="button" ng-click="search()">Search</button>
</section>
<section ng-show="!resultsHidden">
    <div class="no-recipes" ng-hide="players.length">No results</div>
    <article class="playerSearch" ng-repeat="player in players | filter: filter" ng-cloak>
        <h2>
            <a href="#/players/{{player._id}}">{{player.name}}</a>
        </h2>
    </article>
</section>

Javascript:

$scope.myFilter = function (player) {
            var found = [];
            for(player in players) {
                if (player.name === $scope.searchTerm || player.number === $scope.searchTerm){
                    found.push(player);
                }
            }
            return found;
        };
        function search(){
            $scope.filter = $scope.searched;
            $scope.resultsHidden = false;
        }
        $scope.searched = function(player){
            if (!$scope.searchTerm || (player.number == $scope.searchTerm || (player.name.toLowerCase().indexOf($scope.searchTerm.toLowerCase()) != -1))){
                return true;
            }
            return false;
        };

var app = angular.module("app",[])
app.controller('ctrl',['$scope', function($scope){
      $scope.resultsHidden = false;
$scope.players = [
{"name": "alpha"},
{"name": "beta"},
{"name": "gama"}
];   
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  
  <section class="searchField">
        <input type="text" ng-model="searchTerm">
        <button type="button" ng-click="filter = searchTerm;resultsHidden = !resultsHidden">Search</button>
</section>
<section ng-show="resultsHidden">
    <div class="no-recipes" ng-hide="players.length">No results</div>
    <article class="playerSearch" ng-repeat="player in players  | filter:{name:filter}" ng-cloak>
        <h2>
            <a href="#/players/{{player._id}}">{{player.name}}</a>
        </h2>
    </article>
</section>
</div>

试试这个

   <button type="button" ng-click=" filter = searchTerm">Search</button>

首先,您应该创建这样的过滤器:

angular.module('myApp')
.filter('my-filter', function( /* dependencies goes here */ ){
    return function (input, isFilterActive) {
        if (isFilterActive){
            // filter your data
            // your list will go into 'input' variable
            // return filtered list
        }
        return input; //return data unfiltered;
    }

});

你的html应该是这样的:

<p ng-repeat="x in subcategories | my-filter:isFilterActive">
  {{x.text}}
</p>

其中"isFilterActive"变量可以放在$scope上。如果"isFilterActive"为true,则将筛选您的列表。你可以创建一个按钮来改变它的值。

您也可以检查角度过滤器以了解更多详细信息或本教程:https://scotch.io/tutorials/building-custom-angularjs-filters

玩得开心。