这是我的代码,我不知道为什么它不起作用:
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'的名称。
非常感谢您的回答!
答案 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>