首页 > Web开发 > 详细

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

时间:2017-03-01 00:46:10      阅读:220      评论:0      收藏:0      [点我收藏+]

技术分享

实现代码如下

<!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>

 

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

原文:http://www.cnblogs.com/zjf-1992/p/6481506.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!