服务Service
1.常用内置服务
服务 | 说明 |
---|---|
$scope | 作用域,当前控制器内有效 |
$rootScope | 根作用域,当前模块(所有控制器)可用,相当js的全局变量 |
$http | 读取远程服务器的数据,常用有: $http.get({url:'',config}).then(successCallback,errorCallback); $http.post({url:'',data,config}).then(successCallback,errorCallback); |
$location | 相当window.location,常用方法: $location.absUrl()----完整url $location.path()----子路径,不包括参数 $location.url()---- 子路径包括参数 $location.protocol()----请求协议(http、https) $location.search()----获取当前url的参数的序列化json对象 注:1.方法不带参数为获取 2.带参数为修改 小心踩坑:添加模块配置 app.config(['$locationProvider', function ($locationProvider) { |
$timeout | 相当于window.setTimeout,使用:$timeout(function(){},220); |
$intival | 相当于window.setIntival ,,使用:$intival(function(){},220); |
2.自定义服务
定义:app.service('servicename',function(){ this.name='servicename'; this.f1=function(x){return x};this.f2=function(x){return x}; } );
注意:服务属性或方法前要加this
<html ng-app="myApp">
<head>
<title>服务</title>
<base href="/" /><!--注意不加会出错!!!-->
<script src="angular.js" charset="utf-8"></script>
<script>
//创建一个模块 myApp
let app = angular.module('myApp', []);
//这段就是用来让$location可以获取到url的
app.config(['$locationProvider', function ($locationProvider) {
$locationProvider.html5Mode(true);
}]);
//在模块 myApp 在创建一个控制器 main
app.controller('main',function($scope,$location,customService){
//$location 服务常用方法
$scope.absUrl=$location.absUrl();
$scope.path=$location.path();
$scope.url=$location.url();
$scope.search=$location.search();
console.log($location);
//自定义服务使用
$scope.cc=customService.multi(10.5,2.2);
});
//自定义 服务
app.service('customService',function(){
//属性
this.name='customService';
//方法
this.multi=function(x,y){return parseFloat(x)*parseFloat(y);};
});
</script>
</head>
<body ng-controller="main">
$location.absUrl(): {{absUrl}} <br/>
$location.path(): {{path}} <br/>
$location.url(): {{url}} <br/>
$location.search(): {{search}} <br/><br/>
customService.multi(10.5,2.2): {{cc}}<br/>
</body>
</html>
上一篇 angular 笔记(三)过滤器 下一篇 angular 笔记(五) 表单验证