如何通过单击Angular jS中的搜索按钮来搜索项目

时间:2017-03-27 10:24:36

标签: javascript angularjs

我想通过使用角度js单击按钮来搜索项目。我是角度j的初学者。任何人都可以帮我解决这个问题。

我添加了几行代码

视图

<div class="col-lg-8 col-md-8 col-sm-6 col-xs-6 search_button" style="padding: 0;height:45px;" ng-init="search_bar()">
      <input type="hidden" name="search_param" value="all" id="search_param">         
      <input type="text" class="form-control" name="x" placeholder="Search term..." style="height:100%;border-radius: 0;" ng-model="item.searchString" >
      <ul class="data-ctrl">
           <li ng-repeat="i in item | searchFor:searchString">
                <p>{{herllo}}</p>
           </li>
      </ul>
  </div>
  <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1" style="padding: 0;" >
   <span class="input-group-btn">
       <button class="btn btn-default btn-red" type="button"  style="height:45px;color:#fff;border:0px solid #FBA823;    border-radius: 0 5px 5px 0;" ng-click="search_bar()">
       <b>Search</b>
       </button>
   </span>
  </div>

角度js控制器

  $scope.search_bar = function() {

        $http.get('data.json').success(function(data) {
            //alert();
            if($scope.item === 0 )
            {
                alert("Please Enter search keyword");
            }
            else{
                $scope.item = data;
            }
        }).error(function(data, status, headers, config) {
                console.log("No data found..");
        });

    };

服务请求文件是

 app.filter('searchFor', function(){
return function(arr, searchString){
    if(!searchString){
        return arr;
    }
    var result = [];
    searchString = searchString.toLowerCase();
    angular.forEach(arr, function(item){
        if(item.title.toLowerCase().indexOf(searchString) !== -1){
        result.push(item);
    }
    });
    return result;
};
});

1 个答案:

答案 0 :(得分:0)

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

myApp.controller('ctrl', ['$scope', function($scope) {
  $scope.items = [{name:'John', phone:'555-1276'},
                         {name:'Mary', phone:'800-BIG-MARY'},
                         {name:'Mike', phone:'555-4321'},
                         {name:'Adam', phone:'555-5678'},
                         {name:'Julie', phone:'555-8765'},
                         {name:'Juliette', phone:'555-5678'}]
}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
<label>Search: <input ng-model="searchText"></label>
<table id="searchTextResults">
  <tr><th>Name</th><th>Phone</th></tr>
  <tr ng-repeat="friend in items | filter:searchText">
    <td>{{friend.name}}</td>
    <td>{{friend.phone}}</td>
  </tr>
</table>
</div>
&#13;
&#13;
&#13;

Angularjs https://docs.angularjs.org/api/ng/filter/filter

中有一个过滤器模块

这是你需要的吗?