如何在Angularjs中触发输入按钮后在文本框中搜索记录?

时间:2017-01-17 10:42:59

标签: angularjs

在这段代码中,当我输入要在文本框中搜索的记录名称时,我需要在输入时搜索记录,然后单击输入按钮,它应该搜索记录名称。

<input type="text" class="form-control" name="search" placeholder="Enter keyword to search" ng-model="Google" style="background-color:#5b2c2c;color:white;">
<table  class="table" border="1" style="margin:0;margin-left:90px;background-color:white;width:80%;border:5px solid green">
   <thead>
      <tr>
         <th><a>Google</a></th>
         <th><a>Facebook</a></th>
         <th><a>Twitter</a></th>
         <th><a>Yahoo</a></th>
      </tr>
   </thead>
   <tbody>
      <tr ng-repeat="record in collection | filter:Google" ng-class-even="'stripped'">
         <td>{{record.Google}}</td>
         <td>{{record.Facebook}}</td>
         <td>{{record.Twitter}}</td>
         <td>{{record.Yahoo}}</td>
      </tr>
   </tbody>
</table>

<script>
 var app = angular.module('myapp', []);
 app.controller('myctrl', function($scope) {
     $scope.collection = [{
             Google: 'Dhoni',
             Facebook: 'Simla',
             Twitter: '5000'
         },
         {
             Google: 'Kohli',
             Facebook: 'Manali',
             Twitter: '15000'
         },
         {
             Google: 'Virat',
             Facebook: 'Rajasthan',
             Twitter: '35000'
         },
         {
             Google: 'Yuvraj',
             Facebook: 'Kerala',
             Twitter: '35000'
         },
         {
             Google: 'Singh',
             Facebook: 'Mysore',
             Twitter: '35000'
         },
         {
             Google: 'Murali',
             Facebook: 'OOTY',
             Twitter: '20000'
         },
         {
             Google: 'Vijay',
             Facebook: 'Goa',
             Twitter: '20000'
         }
     ];
 });
</script>

4 个答案:

答案 0 :(得分:1)

<input type="text" class="form-control" name="search" placeholder="Enter keyword to search" ng-model="searchText" style="background-color:#5b2c2c;color:white;">
<button ng-click="Google=searchText">Search</button>

答案 1 :(得分:1)

您可以使用控制器内部的过滤器和点击按钮调用功能轻松完成。这里$ scope.Search是完成过滤器的文本。和item是设置过滤器的项目!

    $scope.searchMe = function(){
       $scope.items = $filter('filter')($scope.items, $scope.search);
   }

不要忘记在控制器中注入$ filter。

答案 2 :(得分:1)

<input type="text" class="form-control" name="search" placeholder="Enter keyword to search" ng-model="searchText" style="background-color:#5b2c2c;color:white;">

<tr ng-repeat="record in collection | filter:Google" ng-class-even="'stripped'">
<button ng-click="Google.Facebook=searchText">Search</button> // filter facebook column only
<button ng-click="Google=searchText">Search</button> // can filter any column

答案 3 :(得分:0)

<input type="text" ng-model="searchText" ng-keyPress="filterbyKeyword($event)" placeholder="Enter keyword to search" />

$scope.filterbyKeyword=function(event)
{
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode=='13')
    {
        //your code 
    }
}