过滤以从表AngularJS中删除一些数据

时间:2018-07-29 15:40:28

标签: angularjs filter

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

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>

我要在单击按钮后删除所有带有'Sparrow'的名称。

非常感谢您的回答!

1 个答案:

答案 0 :(得分:1)

您需要将过滤器带到控制器之外。

演示

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>