gpt4 book ai didi

javascript - ng-table 从范围中过滤串联值

转载 作者:行者123 更新时间:2023-11-28 00:44:47 25 4
gpt4 key购买 nike

我使用 ngTable 在 AngularJs 中创建了一个应用程序,我使用 ngTable 来显示用户数据,根据要求,我必须使用表中的单个列来按名字和姓氏进行过滤,它们以$scope分隔”,然后我将结果连接到表格单元格上。但我无法通过串联进行过滤。

我尝试按照http://bazalt-cms.com/ng-table/example/11上的概述创建一个自定义过滤器来完成此任务,但到目前为止尚未成功。

我可以在接收数据时通过循环数组来修改范围,但结果集预计会非常大,我认为这不是正确的方法。

下面是一个简化的示例。是否有一种“Angular Way”可以使用模型或过滤器按连接字符串进行过滤?

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

app.controller('IndexCtrl', function ($scope, $filter, ngTableParams) {
$scope.people = [{
"id": 1,
"firstName": "Chuck",
"lastName": "Norris",
}, {
"id": 2,
"firstName": "John",
"lastName": "Lennon",
}, {
"id": 3,
"firstName": "Bender",
"lastName": "Rodriguez",
}];
$scope.peopleCopy = $scope.people;
$scope.mytable = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
name: 'desc'
}

}, {
getData: function ($defer, params) {
$scope.people = angular.copy($scope.peopleCopy);
var filteredData = $filter('filter')($scope.people, params.filter());
$scope.people = $filter('orderBy')(filteredData, params.orderBy());
$defer.resolve($scope.people);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="http://bazalt-cms.com/assets/ng-table/0.3.0/ng-table.js"></script>
<body ng-app="app">
<div ng-controller="IndexCtrl">
<table border="1" ng-table="mytable" show-filter="true">
<tr ng-repeat="person in $data">
<td sortable="id" data-title="'Id'">{{person.id}}</td>

<!--td I want to sort by firstName + lastName -->
<td sortable="firstName" filter="{ 'firstName': 'text' }" data-title="'Name'">{{person.firstName +' '+ person.lastName}}</td>
</tr>
</table>
</div>
</body>

最佳答案

您可以创建一个查看这两个字段的过滤器函数

 $scope.people = [{
"id": 1,
"firstName": "Chuck",
"lastName": "Norris",
}, {
"id": 2,
"firstName": "John",
"lastName": "Lennon",
}, {
"id": 3,
"firstName": "Bender",
"lastName": "Rodriguez",
}];

$scope.filterLastAndFirst= function(person, searchParam){
return person.firstName.indexOf(searchParam) !== -1 || person.lastName.indexOf(searchParam) !== -1;
};

<li ng-repeat="item in products | filterLastAndFirst: searchParam">{{item.name}}</li>
// where $scope.searchParam is defined

或者过滤器

app.filter('lastAndFirstFilter', function(){
return function(objectArray, searchParam){
var toReturn = [];
// parse the array and search for a parameter.
angular.forEach(objectArray, function(value){
if(value.lastName.indexOf(searchParam) !== -1 || value.firstName.indexOf(searchParam) !== -1)
toReturn.push(value);
});
return toReturn; // return the array
}
});

// used like this:
var filtered = $filter('lastAndFirstFilter')($scope.people, searchTerm);

关于javascript - ng-table 从范围中过滤串联值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27529917/

25 4 0