Top

Angular中$watch实现控件改变后实时发送HTTP请求

实现代码如下

<!DOCTYPE html>
<html ng-app="myServiceApp">
	<head>
		<meta charset="UTF-8">
		<title>$watch实现input监听--并向后台发出HTTP请求</title>
		<!--引入第三方样式库bootstrap.min.css-->
		<link rel="stylesheet" href="framework/bootstrap-3.0.0/css/bootstrap.min.css" />
		<link rel="stylesheet" href="css/main.css" />
		<!--引入js库anglarjs-->
	    <script type="text/javascript" src="framework/angular-1.5.5/angular.js"></script>	
	    <script type="text/javascript" src="js/service.js"></script>
	</head>
	<body>
		<div class = "form-group col-sm-6 main" ng-controller="ServiceController"> 
	     	<label for = "name" class="pull-left">用户名</label> 
	     	<input type = "text" class = "form-control" ng-model="userName" placeholder = "用户名"/>
	     	<div class="pad-t-5">
		     	<table class="table table-bordered table-hover">  
					  <thead>  
					    <tr>  
					      <th>序号</th>  
					      <th>用户名</th>
					      <th>年龄</th>  
					      <th>电话号码</th>
					      <th>所在部门</th>
					    </tr>
					  </thead>  
					  <tbody>  
						  <tr ng-repeat="users in usersList">  
							    <td>{{$index+1}}</td> 
							    <td>{{users.userName}}</td> 
							    <td>{{users.age}}</td>  
							    <td>{{users.phoneNumber}}</td>
							    <td>{{users.department}}</td> 
						    </tr>
					  </tbody>  
			    </table>
		    </div>
	   </div>
	</body>
</html>

service.js

<script type="text/javascript">
	var myService = angular.module('myServiceApp',[]);
	//共用的controller抽成Service
	myService.factory('userListService', ['$http', 
    	function($http){
    		//doRequest处理请求
    		var doRequest = function(userName, path){
    			return $http({
    				method: 'GET',
		            url: 'cardInfo/users.json'
    			});
    		}
    		return {
    			userList : function(userName){
    				return doRequest(userName, 'userList');
    			}
    		}
    	}
	]);
	
	//控制器调用service
	myService.controller('ServiceController', ['$scope','$timeout', 'userListService', 
    	function($scope, $timeout, userListService){
    		//监听数据模型ng-model
    		var timeout;
    		$scope.$watch('userName', function(newUserName){
    			if(newUserName){
    				if(timeout){
    					$timeout.cancel();
    				}
    			}
    			timeout = $timeout(function(){
    				userListService.userList(newUserName).success(function(data, status){
    					$scope.usersList = data;
    				})
    			},350)
    		});
    	}
	]);
</script>

 

posted @ 2017-02-28 23:00  Avenstar  阅读(769)  评论(0编辑  收藏  举报