angularJS中搜索框的用法

  angularJS的强大数据绑定功能让一键搜索成为可能,摒弃繁琐的button,让我们一起看一下让喝让搜索逆袭!

  首先,HTML页面引入input,

  

<div class="form-horizontal" ng-controller="ServiceController">
    <form>
<label for="kw" class="sr-only">请输入您要搜索的关键字</label>

<div class="col-xs-4">
<input class="form-control" id="kw" placeholder="search..." ng-model="kw">
</div>
</form>
<button type="text" class="btn btn-warning pull-right header-adjust">导出Excel</button>
</div>

  当然,借助H5,你的type="search"会更完美一点.

  接下来,你要监听input搜索框的信息  

 

    app.controller('ServiceController', function($scope,) { 
        $scope.$watch('username', function(newUserName) {...}

       }

  这样,你就很好的监听了你的数据变化。但这同时会产生一个问题,高频率的监听会耗损你的效率,下面,我们做最后的完善,让数据"智能"监听。

    

      app.controller('ServiceController', function($scope, $timeout, githubService) { // 添加了$timeout服务
      var timeout;
      $scope.$watch('username', function(newUserName) {

      if (newUserName) { 11 // 如果在进度中有一个超时(timeout)
      if (timeout) $timeout.cancel(timeout);
      timeout = $timeout(function() {

        githubService.events(newUserName)

          .success(function(data,status){

      $scope.events=data.data;

      })

      }, 350); }

      }); }); 

      

  ok,现在,如果用户两次输入之间有350 ms的间 隔,就推断用户已经完成了输入,然后开始向GitHub发送请求 。

  

原文地址:https://www.cnblogs.com/qinglingyue/p/5163436.html