1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Service</title>
6 </head>
7 <body ng-app="app" ng-controller="myCtrl">
8
9 <input type="text" ng-model="cont" >
10 <hr>
11 <button ng-click="get()">Get</button>
12
13 <ul ng-show="user">
14 <li>{{user.id}}</li>
15 <li>{{user.name}}</li>
16 <li>{{user.age}}</li>
17 </ul>
18
19
20 <script src="bower_components/angular/angular.js"></script>
21
22 <script>
23
24 var app = angular.module("app",[]);
25
26 // app.controller("myCtrl",["$scope","$http",function ($scope,$http) {
27 // $scope.get=function () {
28 // $http({
29 // method:'GET',
30 // url:'data.json'
31 // }).then(function suc(response) {
32 // $scope.user=response.data;
33 // console.log(response);
34 // });
35 // }
36 // }])
37
38
39
40 // app.controller("myCtrl",["$scope","$timeout","$http",function ($scope,$timeout,$http) {
41 // var timer;
42 // $scope.$watch("cont",function (newCont) {
43 // if(newCont) {
44 // if(timer){
45 // $timeout.cancel(timer);//延时500毫秒后请求数据,避免频繁的请求
46 // }
47 // timer = $timeout(function () {
48 // $http({
49 // method: 'GET',
50 // url: 'data.json'
51 // }).then(function suc(response) {
52 // $scope.user = response.data;
53 // console.log(response);
54 // });
55 // },500);//延时500毫秒后请求数据,避免频繁的请求
56 //
57 // }
58 // })
59 // }])
60
61 //自定义服务
62 app.factory("GetService",["$http",function ($http) {
63 return {
64 doget:function (url) {
65 return $http({
66 method: 'GET',
67 url: url
68 });
69 }
70 }
71 }]);
72 //自定义服务,放在最后一个参数中
73 app.controller("myCtrl",["$scope","$timeout","$http","GetService",function ($scope,$timeout,$http,GetService) {
74 var timer;
75 $scope.$watch("cont",function (newCont) {
76 if(newCont) {
77 if(timer){
78 $timeout.cancel(timer);//延时500毫秒后请求数据,避免频繁的请求
79 }
80 timer = $timeout(function () {
81 //使用自定义服务
82 GetService.doget('data.json').then(function suc(response) {
83 $scope.user = response.data;
84 console.log(response);
85 });
86 },500);//延时500毫秒后请求数据,避免频繁的请求
87 }
88 })
89 }])
90
91
92 </script>
93
94 </body>
95 </html>