1.服务 #

angular会自动创建实例并注入,不需要手工创建 service在整个应用的生命周期存在,可以共享数据

1.1 provider #

可配置,是唯一一种你可以传进 .config() 函数的 service

1.1.1 提供计算的服务 #

<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>

1.1.2 创建服务 #

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),
           }
       }
});

1.1.3 使用服务 #

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);
    }
});

1.1.4 配置服务 #

app.config(function (myProviderProvider) {
        myProviderProvider.currency='$'
});

在模块上进行配置

var app = angular.module('appModule',[], function (myProviderProvider) {
    myProviderProvider.currency='$'
});

1.2 factory #

工厂函数定义服务,调用该工厂函数将返回服务实例

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),
       }
});

1.3 service #

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);
});

1.4 constant #

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 = '$';
});

1.5 value #

app.value('myvalue', {
      '+':(a,b)=>(a+b),
      '-':(a,b)=>(a-b),
      '*':(a,b)=>(a*b),
      '/':(a,b)=>(a/b),
});

1.6 decorator #

1.6.1 声明服务 #

app.factory('my',function () {
    return {
        a: function () {
            return 1;
        }
    };
});

1.6.2 装饰服务 #

app.config(function ($provide) {
    $provide.decorator('my',function ($delegate) {
        var fn =  $delegate['a'];
        $delegate['a'] = function () {
            return fn()+100;
        };
        return $delegate;
    });
});