一、服務?
AngularJS功能最基本的組件之一是服務(Service)。服務爲你的應用提供基於任務的功能。服務可以被視爲重複使用的執行一個或多個相關任務的代碼塊。
AngularJS服務是單例對象,這意味着只有一個實例被創建過,服務使用AngularJS的依賴注入機制來定義和註冊。
可以把服務注入模塊、控制器和其它服務。
二、內置服務
$http 發送http請求
$resource 創建一個可以RESTful服務器端數據源交互對象
$window 瀏覽器的window元素的jQuery包裝
$document 瀏覽器的document元素的jQuery包裝
$rootScope 根作用域的訪問
$rootElement 根元素的訪問
$cacheFactory 提供鍵/值對放置到對象緩存
$interval 提供對window.setInterval訪問
$timeout 提供對window.setTimeout訪問
$cookies 提供對瀏覽器的cookie的讀寫訪問
$animate 提供動畫鉤子來同時鏈接到以CSS和JavaScript爲基礎的動畫
2.1 $http
內置服務$http
內置服務,Angular提供了很多,在使用的時候
通過依賴注入的方式在組件、控制器、自定義指令、run()函數等等中使用
$http 是一個特殊的內置服務,主要用於進行異步數據請求的功能實現
語法:
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
});
案例1:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>$http</title>
<script type="text/javascript" src="js/lib/angular.min.js" ></script>
</head>
<body>
<div ng-controller="myCtrl">
<ul>
<li ng-repeat="g in goodsList">
<span ng-bind="g.classID"></span>***
<span ng-bind="g.className"></span>
</li>
</ul>
</div>
</body>
<script>
var app=angular.module("myApp",[]);
app.controller("myCtrl",["$scope","$http",function($scope,$http){
$scope.goodsList=[]; //保存所有商品的數組 不寫也可以
//異步請求獲取數據
$http({
method:"GET",
url:"http://datainfo.duapp.com/shopdata/getclass.php"
}).then(
function success(resp){
console.log(resp);
$scope.goodsList=resp.data;
},
function error(resp){
console.log("errorLLLLLL"+resp);
}
);
}]);
</script>
</html>
<!DOCTYPE html>
<html ng-app="myAPP">
<head>
<meta charset="UTF-8">
<title>登錄</title>
<script src="js/lib/angular.min.js" ></script>
</head>
<body>
<div class="form" ng-controller="login">
賬號:<input type="text" ng-model="username"/><br />
密碼:<input type="text" ng-model="password"/><br />
<button ng-click="loginFn()">登錄</button>
</div>
</body>
<script>
var app=angular.module("myApp",[]);
app.controller("login",["$scope","$http",function($scope,$http){
$scope.loginFn=function(){
$http({
method:"GET",
url:"http://datainfo.duapp.com/shopdata/userinfo.php",
params:{
status:"login",
userID:$scope.username,
password:$scope.password
}
}).then(
function success(resp){
console.log("請求成功",resp);
if(resp.data){
console.log("登陸成功,跳轉到首頁");
}else{
console.log("登錄失敗");
}
},
function error(resp){
console.log("請求失敗");
}
);
}
}]);
</script>
</html>
用圖片來解釋上面的代碼: