搜索框 展示相关搜索内容列表,及延迟改进(仿百度)

实现的功能如下图:

DOM代码一样:

<fieldset>
  <legend>模拟百度搜索-$http</legend>
  <div>
    <input type="text" ng-model = 'wd' ng-keyup = 'search(wd)'>   //键盘抬起触发事件
    <input type="button" value="搜索" ng-click = 'search(wd)'>    //点击按钮同样触发事件
    <ul style = "height:200px;border: 1px solid red;width:300px;">     //显示搜索结果内容
      <li ng-repeat = "data in datalist">{{data}}</li>
    </ul>
  </div>
</fieldset>

 

版本一:(low)

说明: 在每次按键抬起都会触发请求(比如,输入 angular,会触发7次搜索结果),造成浪费,影响加载速度。

$scope.search = function(wd){
  $http({
    method:'JSONP',
    url:'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=' + wd + '&cb=JSON_CALLBACK',
  }).success(function(data){
    $scope.datalist = data.s;
  })
}

 版本一:(高大上)

说明:短暂延时,在连续快速输入(<500ms)时,不会触发请求,停顿时间>500ms时,才会一次性发送请求。

$scope.timer = null;
$scope.search = function(wd){
  $timeout.cancel($scope.timer); //联系快速输入时,取消定时器,不触发
  $scope.timer = $timeout(function(){   //延时发送请求
	$http({
	  method:'JSONP',
	  url:'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=' + wd + '&cb=JSON_CALLBACK',
	}).success(function(data){
	  $scope.datalist = data.s;
	})
  }, 500);	
}

 

posted @ 2017-06-02 17:21  若鱼灬  阅读(387)  评论(0编辑  收藏  举报