service 自定義服務(wù)
1.指令
- 內(nèi)置指令
- 自定義指令
app.directive('xmg',function(){
return {
//指令類型
restrict:'EA',
//指令模版
template:'',
//是否替換原有指令
replace:'true',
//是否保留標(biāo)簽內(nèi)容
transclude:'true'
}
})
2.過(guò)濾器
- 內(nèi)置過(guò)濾器
- 自定義過(guò)濾器
app.filter('filterName',function(){
return function(input){
}
})
3.服務(wù)
- 內(nèi)置服務(wù)
- 自定義服務(wù)
- angular 在一開始就幫我們定義一些功能,我們可以直接使用這些功能例证,都是一個(gè)方法或者一個(gè)對(duì)象的形式來(lái)調(diào)用指定的功能爸舒。想要使用這些服務(wù)冗酿,必須要注入画拾。所謂 服務(wù) 是將一些通用性的功能邏輯進(jìn)行封裝方便使用,angularJs 允許自定義服務(wù)
- 自定義服務(wù)目的:把公用的功能邻耕,給封裝到一起戴甩,進(jìn)行復(fù)用
- 服務(wù)本質(zhì)就是一個(gè)對(duì)象,或者以方法方式存在
- 注意系統(tǒng)內(nèi)置服務(wù)前加 $ 谤祖,自定義服務(wù)的不需要加
app.service('xmgService',function(){
this.say=function(){
console.log('hello');
}
this.showTime = function(){
var curTime = new Date();
}
})
app.service('xmgService',function($filter){
this.say = function(){
console.log('hello');
}
this.showTime = function(){
var curTime = new Date();
//var date = $filter('date');
//return date(curTime,'yyyy-MM-dd hh:mm:ss')
return $filter('date')(curTime,'yyyy-MM-dd hh:mm:ss');
}
})
factory 自定義服務(wù)
var app = angular.module('app',[]);
app.controller('skController',['$scope',function($scope){
myFactory();
myFactory2.myTime();
myFactory2.say();
}])
app.factory('myFactory',function(){
return function(){
console.log('執(zhí)行了myFactory')
}
})
app.factory('myFactory2',function(){
function showTime(){
console.log('執(zhí)行了myFactory2')婿滓;
}
function mySay(){
console.log('hello');
}
return {
myTime:showTime,
say:mySay
}
})
服務(wù)的參數(shù)格式化
- 將 json 格式 轉(zhuǎn)化成 formData 格式
原來(lái) post 請(qǐng)求格式, 傳參使用不方便
$http({
url:'post.php',
method:'post',
data:'name=sk&age=666'
})
//考慮將 josn 對(duì)象參數(shù)格式轉(zhuǎn)化成 formData 形式
方式一
app.factory('formData',function(){
return function(obj){
var res ='';
for(key in obj){
res += key + '=' +obj[key] + '&';
}
//最后一位多了一個(gè)&
res = res.slice(0,-1);
return res;
}
})
方式二
app.factory('formData2',function(){
function formDataPost(obj){
var res = '';
for(key in obj){
res += key+ "=" +obj[key] +'&';
}
res = res.slice(0,-1);
return res;
}
return {
dataPost:formDataPost
}
})
方法三自定義服務(wù)
app.service('formDataService',function(){
this.form = function(obj){
var res = '';
for(key in obj){
res += key + '=' + obj[key] + '&'
}
res=res.slice(0,-1);
return res;
}
})
- 使用函數(shù)
var param ={
name:'sk',
age:666
}
$http({
url:'post.php',
method:'post',
//方式一
data:formData(param)
//方式二
data:formData2.dataPost(param)
//方式三
data:formDataService.form(params)
})
value 自定義服務(wù)
- value 表現(xiàn)形式上是一個(gè)服務(wù)
- 本質(zhì)上可看作是一個(gè)常量粥喜,到那時(shí)以服務(wù)的方式使用
app.controller('skController',["$scope","userName",function($scope,$userName){
console.log(userName);
$scope.name = 'aaa';
}])
app.value('userName','sk')