您的位置:首页 > Web前端 > AngularJS

angularJS中搜索框的用法

2016-01-27 15:29 711 查看
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发送请求 。

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: