首页 > 解决方案 > 过滤以从表 AngularJS 中删除一些数据

问题描述

这是我的代码,我不知道为什么它不起作用:

JS:

$scope.names = [{"name" : "John_Sparrow"},
{"name" : "Jack_Black"},
{"name" : "Eva_Sparrow"}]

app.filter('FilterFunction',function(){
    return function(data, input) {
        if (!input) return data;
        var datas = [];
        angular.forEach(data, function(item){
            if(!(item.name.includes('Sparrow'))) {
                datas.push(item);
            }
        });
        return datas;
    };
});

HTML:

 <table class="table table-bordered table-striped">
  <thead>
   <tr> 
    <th>Name</th>
   </tr>
  </thead>
  <tbody>
   <tr ng-repeat="name in names |FilterFunction:input">
    <td>{{name.name}}</td>
   </tr>
  </tbody>
</table>


<button class="btn btn-clear" ng-click="input = !input;">delete_sparrow</button>

单击按钮后,我想删除所有带有“麻雀”的名称。

提前谢谢解答!!!

标签: angularjsfilter

解决方案


您需要将过滤器放在控制器之外。

演示

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

app.controller('HelloWorldCtrl', function($scope){

$scope.names = [{"name" : "John_Sparrow"},
{"name" : "Jack_Black"},
{"name" : "Eva_Sparrow"}];

});

app.filter('FilterFunction',function(){
    return function(data, input) {
        if (!input) return data;
        var datas = [];
        angular.forEach(data, function(item){
            if(!(item.name.includes('Sparrow'))) {
                datas.push(item);
            }
        });
        return datas;
    };
});
<!DOCTYPE html>
<html ng-app="app">
  <head>
    <script data-require="angular.js@*" data-semver="4.0.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />     
  </head>

  <body ng-controller="HelloWorldCtrl">
<table class="table table-bordered table-striped">
  <thead>
   <tr> 
    <th>Name</th>
   </tr>
  </thead>
  <tbody>
   <tr ng-repeat="name in names |FilterFunction:input">
    <td>{{name.name}}</td>
   </tr>
  </tbody>
</table>


<button class="btn btn-clear" ng-click="input = !input;">delete_sparrow</button>
   
  </body>

</html>


推荐阅读