angular会自动创建实例并注入,不需要手工创建 service在整个应用的生命周期存在,可以共享数据
可配置,是唯一一种你可以传进 .config() 函数的 service
<div class="col-lg-4 col-lg-offset-4 form-group" ng-controller="ctrl as vm ">
<input type="text" class="form-control" ng-model="vm.a">
<select name="" id="" class="form-control" ng-model="vm.select">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" class="form-control" ng-model="vm.b">
<button class="btn btn-primary" ng-click="vm.computed()">=</button>
{{vm.value}}
</div>
app.provider('myProvider', function () {
this.currency = '¥';
this.$get = function () {
return {
'+':(a,b)=>this.currency+(a+b),
'-':(a,b)=>this.currency+(a-b),
'*':(a,b)=>this.currency+(a*b),
'/':(a,b)=>this.currency+(a/b),
}
}
});
app.controller('ctrl', function (myProvider) {
this.computed = function () {
console.log(myProvider[this.select](parseInt(this.a),parseInt(this.b)));
this.value = myProvider[this.select](this.a,this.b);
}
});
app.config(function (myProviderProvider) {
myProviderProvider.currency='$'
});
在模块上进行配置
var app = angular.module('appModule',[], function (myProviderProvider) {
myProviderProvider.currency='$'
});
工厂函数定义服务,调用该工厂函数将返回服务实例
app.factory('myfactory', function () {
var currency = '$';
return {
'+':(a,b)=>currency+(a+b),
'-':(a,b)=>currency+(a-b),
'*':(a,b)=>currency+(a*b),
'/':(a,b)=>currency+(a/b),
}
});
app.service('myservice', function () {
var currency = '$';
this['+']=(a,b)=>currency+(a+b);
this['-']=(a,b)=>currency+(a-b);
this['*']=(a,b)=>currency+(a*b);
this['/']=(a,b)=>currency+(a/b);
});
app.constant('myconstant', {
'+':(a,b)=>(a+b),
'-':(a,b)=>(a-b),
'*':(a,b)=>(a*b),
'/':(a,b)=>(a/b),
});
可配置
app.config(function (myconstant) {
myconstant.aa = '$';
});
app.value('myvalue', {
'+':(a,b)=>(a+b),
'-':(a,b)=>(a-b),
'*':(a,b)=>(a*b),
'/':(a,b)=>(a/b),
});
app.factory('my',function () {
return {
a: function () {
return 1;
}
};
});
app.config(function ($provide) {
$provide.decorator('my',function ($delegate) {
var fn = $delegate['a'];
$delegate['a'] = function () {
return fn()+100;
};
return $delegate;
});
});