【问题标题】:Filter to remove some data from table AngularJS过滤以从表 AngularJS 中删除一些数据
【发布时间】:2018-07-29 15:40:27
【问题描述】:

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

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”的名字。

提前感谢您的回答!!!

【问题讨论】:

  • 可能很简单:&lt;tr ng-repeat="name in names" ng-if='name.name.indexOf("Sparrow") === -1'&gt;?

标签: angularjs filter


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 2021-09-06
    • 2014-09-05
    • 2013-08-16
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多