<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Service</title>
</head>
<body ng-app="app" ng-controller="myCtrl"> <input type="text" ng-model="cont" >
<hr>
<button ng-click="get()">Get</button> <ul ng-show="user">
<li>{{user.id}}</li>
<li>{{user.name}}</li>
<li>{{user.age}}</li>
</ul> <script src="bower_components/angular/angular.js"></script> <script> var app = angular.module("app",[]); // app.controller("myCtrl",["$scope","$http",function ($scope,$http) {
// $scope.get=function () {
// $http({
// method:'GET',
// url:'data.json'
// }).then(function suc(response) {
// $scope.user=response.data;
// console.log(response);
// });
// }
// }]) // app.controller("myCtrl",["$scope","$timeout","$http",function ($scope,$timeout,$http) {
// var timer;
// $scope.$watch("cont",function (newCont) {
// if(newCont) {
// if(timer){
// $timeout.cancel(timer);//延时500毫秒后请求数据,避免频繁的请求
// }
// timer = $timeout(function () {
// $http({
// method: 'GET',
// url: 'data.json'
// }).then(function suc(response) {
// $scope.user = response.data;
// console.log(response);
// });
// },500);//延时500毫秒后请求数据,避免频繁的请求
//
// }
// })
// }]) //自定义服务
app.factory("GetService",["$http",function ($http) {
return {
doget:function (url) {
return $http({
method: 'GET',
url: url
});
}
}
}]);
//自定义服务,放在最后一个参数中
app.controller("myCtrl",["$scope","$timeout","$http","GetService",function ($scope,$timeout,$http,GetService) {
var timer;
$scope.$watch("cont",function (newCont) {
if(newCont) {
if(timer){
$timeout.cancel(timer);//延时500毫秒后请求数据,避免频繁的请求
}
timer = $timeout(function () {
//使用自定义服务
GetService.doget('data.json').then(function suc(response) {
$scope.user = response.data;
console.log(response);
});
},500);//延时500毫秒后请求数据,避免频繁的请求
}
})
}]) </script> </body>
</html>
05-11 15:24
查看更多