您的位置:首页 > Web前端 > AngularJS

[java学习10]angularJS之服务练习

2016-11-02 13:50 381 查看
<!DOCTYPE html>
<html lang="en" ng-app="appService">
<head>
<meta charset="UTF-8">
<title>测试directive</title>
<script src="frameWork/angular.js"></script>
<script src="frameWork/jquery-3.1.0.min.js"></script>
<script src="js/testService.js"></script>
</head>
<body>

<h3>用自带的$http直接读取</h3>
<div ng-controller="serviceCtrl">
<ul>
<li ng-repeat="u in users">名字:{{u.name}};年龄:{{u.age}}</li>
</ul>
</div>

<h3>自定义了封装$http服务,读取</h3>
<div ng-controller="customerServiceCtrl">
<input type="text" ng-model="username">
<ul>
<li ng-repeat="u in users">名字:{{u.name}};年龄:{{u.age}}</li>
</ul>
</div>

</body>
</html>
/**
* Created by liyanq on 16/11/1.
* 目的是练习service
*
* 1,$http
*
*/
var app = angular.module("appService", []);

app.controller("serviceCtrl", function ($scope, $http) {
$http({
method: "GET",
url: "data/serviceData"
}).success(function (data, status, headers, config) {
$scope.users = data;
}).error(function (data, status, headers, config) {
console.log("error....");
});

}).factory("myFirstService", function ($http) {
var doRequest = function (username, path) {
return $http({
method: "GET",
url: "data/serviceData"
})
};
return {
getUserList: function (username) {
return doRequest(username, "/path");
}
}
}).controller("customerServiceCtrl", function ($scope, $timeout, myFirstService) {
var timeOut;
$scope.$watch("username", function (newUsername, oldUserName) {
console.log(newUsername + ";" + oldUserName);
if (newUsername) {
if (timeOut) {
console.log(timeOut);
$timeout.cancel(timeOut);
}
}
timeOut = $timeout(function () {
myFirstService.getUserList("userName")
.success(function (data, status, headers, config) {
$scope.users = data;
}).error(function (data, status, headers, config) {
console.log("error....");
});
}, 300);
});
});
没有过多练习,勉强写了些,以后实际用到的时候再练。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  angular 服务