使用搜索字段过滤ui-grid

时间:2018-03-29 10:26:03

标签: javascript angularjs filter

目前我有一个带有全名和注册列的ui-grid。我也有两个搜索字段。如果用户搜索注册,表格将“即时”更新。我的问题是,如果用户输入两者以缩小搜索范围,例如同时注册和注册名称。该表仅对单个过滤器输入作出反应。

这是我的代码的一部分,负责查看作为搜索字段的字段vm.model.employeeName和vm.model.registrationName。 vm.resultData是要插入到vm.gridOptions.data(ui-grid)中的行数组。

vm.watchFilter = function() {

    if (vm.model.employeeName || vm.model.registrationNumber) {

        if (vm.model.employeeName) {
            vm.updatedResultData = $filter('filter')(vm.resultData, {employeeFullName: vm.model.employeeName});
        }

        if(vm.model.registrationNumber) {
            vm.updatedResultData = $filter('filter')(vm.resultData, {currentVehicleRegistration: vm.model.registrationNumber});
        }

        vm.gridOptions.data = vm.updatedResultData;

    } else {
        vm.gridOptions.data = vm.resultData;
    }
    vm.numberOfRecords = vm.gridOptions.data.length;
};

$scope.$watch('vm.model.employeeName', vm.watchFilter);
$scope.$watch('vm.model.registrationNumber', vm.watchFilter);

如何将2结合起来缩小搜索范围?我花了好几个小时...... 我不想为每个可能的搜索结束if语句,因为我将来可能会添加额外的搜索字段。此外,如果用户决定先输入reg然后命名.....

1 个答案:

答案 0 :(得分:0)

我希望这会对你有所帮助。谢谢。

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

app.controller('pageCtrl', ['$scope', '$http',  function($scope, $http) {  

$scope.names = [{"Name":"Mark","Number":"10000"}, 
                {"Name":"Steve","Number":"20000"}, 
                {"Name":"Bill","Number":"30000"},
                {"Name":"John","Number":"40000"}, 
                {"Name":"Luis","Number":"50000"}];

  $scope.search = function(){
    $scope.criteria = angular.copy($scope.criteria1);
  }
 
  
}]);
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-messages.min.js"></script>



<div ng-app="app" class="container" >
  <h1>Filter Name & Registeration Number</h1>
  <hr />
  
  <form ng-controller="pageCtrl" ng-init='getData()'>
    
    <div class='form-group'>
        <div class='row'>
           <div class="right-inner-addon col-md-4 ">        
            <input type="search" ng-model='model.Name' class="form-control" placeholder="Name">
           </div>
           <div class="right-inner-addon col-md-4 ">        
            <input type="search" ng-model='model.Number' class="form-control" placeholder="Registeration Number">
          </div>
        </div>
    </div>
         
     <table class="table table-bordered" >
       <tr>
         <th>Name</th>
         <th>Registeration Number</th>
       <tr>
       <tr ng-repeat="item in filtered = (names | filter : model)">
         <td>{{item.Name}}</td>
         <td>{{item.Number}}</td>
       <tr>
      </table>    
  </form>
  
</div>