AngularJS并过滤一些特定字段

时间:2014-09-01 09:22:18

标签: javascript angularjs

我有一个Angular应用程序,可以过滤我所拥有的JSON文件中的所有字段。

我有Id, FullName, FirstName, LastName, StartNo, DateOfBirth。我希望能够在Id字段中搜索所有这些字段。

例如,当我写1212时,我会找到包含StartNo 1212的人和ID为1212的人。我不希望能够过滤ID,我该如何删除?我只想拥有一个<input>字段,而不是很多,我可以在哪里设置不同的模型?

对所有相关文档的帮助甚至指示表示赞赏。

看起来像这样。

<input ng-model="searchText">
<table>
<tr ng-repeat=runner in runners | filter:searchText>
<td>{{runner.StartNo}}</td>
<td>{{runner.FirstName}}</td>
<td>{{runner.LastName}}</td>
<td>{{runner.DateOfBirth}}</td>
</tr>
</table>

排序。

1 个答案:

答案 0 :(得分:2)

您可以使用如下所示的正则表达式

来实现
$scope.searchFilter = function (obj) {
        var re = new RegExp($scope.searchText, 'i');
        return !$scope.searchText || re.test(obj.StartNo) || re.test(obj.FirstName)|| re.test(obj.LastName)|| re.test(obj.DateOfBirth);
    };

完整代码如下。

<强> Working JSFiddle

<强> HTML

<div ng-app="myApp">
    <div ng-controller="PeoplesCtrl">
        <form>
            <label>Filter by:</label>
            <input type="text" ng-model="searchText">
            <table>
                <tr>
                    <th></th>
                </tr>
                <tr ng-repeat="runner in runners | filter:searchFilter">
                    <td ng-class-odd="'odd'">{{runner.StartNo}}</td>
                    <td ng-class-odd="'odd'">{{runner.FirstName}}</td>
                    <td ng-class-odd="'odd'">{{runner.LastName}}</td>
                    <td ng-class-odd="'odd'">{{runner.DateOfBirth}}</td>
                </tr>
            </table>
        </form>
    </div>
</div>

<强>脚本

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

myApp.factory('Peoples', function () {
    var Peoples = {};
    Peoples.runners = [{
        Id : "1212",
        StartNo: "001",
        FirstName : "Tony Stark",
        LastName : "Robert",
        DateOfBirth : "12/05/1989"
    },{
        Id : "1213",
        StartNo: "002",
        FirstName : "Chris",
        LastName : "Evans",
        DateOfBirth : "10/01/1988"
    },{
        Id : "1214",
        StartNo: "003",
        FirstName : "Scarlett",
        LastName : "Banner",
        DateOfBirth : "01/05/1990"
    },{
        Id : "1215",
        StartNo: "004",
        FirstName : "Clark",
        LastName : "Robert",
        DateOfBirth : "19/08/1989"
    },{
        Id : "1216",
        StartNo: "005",
        FirstName : "Hiddleston",
        LastName : "Robert",
        DateOfBirth : "22/06/1989"
    }];

    return Peoples;
});

function PeoplesCtrl($scope, Peoples) {
    $scope.runners = Peoples.runners;

    $scope.searchFilter = function (obj) {
        var re = new RegExp($scope.searchText, 'i');
        return !$scope.searchText || re.test(obj.StartNo) || re.test(obj.FirstName)|| re.test(obj.LastName)|| re.test(obj.DateOfBirth);
    };
}