javascript
--@angularJS--自定义服务与后台数据交互小实例
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;
?? ??? ?}
?? ?}
]);
總結
以上是生活随笔為你收集整理的--@angularJS--自定义服务与后台数据交互小实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 项目管理——任务分配闲谈
- 下一篇: 开源点评:Protocol Buffer