1、myService.html:
<!DOCTYPE HTML>
<html ng-app="app">
<head>
<title>自定义服务与后台数据交互</title>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/bootstrap.css">
<script src="../js/angular.js"></script>
<style>
.tip{background: #f2f2f2;border-radius: 6px;box-shadow: 2px 2px 4px #777;width: 200px;height: auto;position: relative;top:-10px;padding: 10px;}
</style>
</head>
<body>
<div ng-controller="myServiceCtrl" ng-click="hideTip()">
<label>用户名</label>
<input type="text" ng-model="username" placeholder="请输入用户名..."/>
<div ng-show="showld" ng-class='{tip: showld}'>
<p ng-repeat="user in users">{{user.name}}</p>
</div>
</div>
<script src="myService.js"></script>
</body>
</html>
2、myService.js:
var myModule = angular.module("app",[]);
myModule.service('userListService', ['$http', function($http){
var doRequest = function(username,path){
return $http({//底层其实还是$http的交互
method:'GET',
url:'data.json'
});
}
return{//一层一层的封装
userList:function(username){
return doRequest(username,'userList');
}
}
}]);
//上面封装的服务其实就是众多controller中与后台文件交互,得到数据的共同代码,提取出来单独封装在公共服务模块里,供后面的控制器直接调用而已
myModule.controller('myServiceCtrl', ['$scope','$timeout','userListService', //注入除作用域外的定时器对象和自定义的服务,注意:angular系统自带的都是带$符的,自定义的是不带$符的
function($scope,$timeout,userListService){
var timeout;//定义延迟变量
$scope.showld = false;
$scope.watch('username',function(newUserName){//监察username,一旦username发生变化,就执行后面的function()函数
if (newUserName) {//如果拿到新用户名,就用自定义服务中的方法进行处理
if (timeout) {//一旦timeout里面有定时器id
$timeout.cancel(timeout);//就清除已经生成过的定时器,cancel()相当于clearTimeOut()方法
}
timeout = $timeout(function(){
userListService.userList(newUserName)
.success(function(data,status){
$scope.users = data;
$scope.showld = true;
});
},350);
};
});
$scope.hideTip = function(){//点击就隐藏提示框,注意不要放在控制器之外了,否则无效
$scope.showld = false;
}
}
]);