AngularJs使用下拉过滤器搜索

时间:2016-06-07 19:39:42

标签: angularjs

您将如何创建精致的搜索?使用下面的代码,过滤器作用于两个列。例如,如果你输入约翰,你将获得John Smith&史密斯约翰。我想使用下拉列表作为过滤器。我查看了其他提到过滤器的帖子:object.value或者什么。

我想我需要将下拉列表设置为一个值,然后将其输入到文本框并过滤到表格。

HTML

<div ng-app="searchApp" ng-controller="searchCtrl">
    <br>
    <br>
    <input type="text" ng-model="searchData">

    <table>
        <thead>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
        </thead>
        <tbody>


            <select>
                <option value="">FilterBy</option>
                <option value="">FirstName</option>
                <option value="">LastName</option>
            </select>



            <tr ng-repeat="name in names | filter:searchData">

                <td>{{name.firstName}}</td>
                <td>{{name.lastName}}</td>
            </tr>
        </tbody>
    </table>
</div>

<script src=" search.js " type="text/javascript "></script>

.JS

 var searchApp = angular.module('searchApp', []);
 searchApp.controller('searchCtrl', function($scope) {

 $scope.names = [
         {"firstName":"John","lastName":"Smith"},
        {"firstName":"Smith","lastName":"John"},
        {"firstName":"John","lastName":"Doe"},
        {"firstName":"Doe","lastName":"Jane"}
      ];



 });

1 个答案:

答案 0 :(得分:3)

我在过滤器下拉列表中添加了ng-change,并在该函数调用上设置了过滤器对象。

<select ng-model="by" ng-change="filter(by)">
 <option value="">FilterBy</option>
 <option value="firstName">FirstName</option>
 <option value="lastName">LastName</option>
</select>


$scope.filter = function(by){
  if(by){
    $scope.filterData = { };
    $scope.filterData[by] = $scope.searchData;  
  }else{
    $scope.filterData = {};
  }
 };

以下是工作示例http://codepen.io/mkl/pen/GqpxGZ

的链接