<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <script src="angular.min.js" ></script>
    <script type="text/javascript">
    var m1 = angular.module(‘myApp‘, []);
    // 自定义服务 -- factory
    // m1.factory(‘myService‘, function() {
    //     return {
    //         name : ‘liuyi‘,
    //         age : 30,
    //         showName : function() {
    //             return this.name + ‘今年‘ + this.age + ‘岁了‘; 
    //         }
    //     };
    // });
    
    // 自定义服务 provider
    m1.provider(‘myService‘, function() {
        return {
            name : ‘刘二‘,
            age : 40,
            $get : function() {
                return {
                    name : this.name,
                    age : this.age,
                    showName : function() {
                        return this.name + ‘今年‘ + this.age + ‘岁了‘; 
                    } 
                };
            }            
        };
    });
    
    // 自定义服务 -- 随机函数
    // m1.factory(‘rndFn‘, function() {
    //     return function( n1, n2 ) {
    //         return Math.random()*(n2 -n1) + n1;
    //     }
    // });
    // 改写配置参数
    // m1.config( [‘myServiceProvider‘, function(myServiceProvider) {
    //     myServiceProvider.age = 100;
    // }] );
    m1.config( [‘randomFnProvider‘, function(randomFnProvider) {
        randomFnProvider.bInt = false;
    }] );
    // 控制器
    // m1.controller(‘firstController‘, [‘$scope‘, ‘rndFn‘, function($scope, rndFn) {
    //     console.log( rndFn( 0, 5 ) );
    // }]);
    
    m1.provider(‘randomFn‘, function() {
        return {
            bInt : false,
            int : function( args ) {
                if( args ) {
                    this.bInt = true;
                } else {
                    this.bInt = false;
                }
            }, 
            $get : function() {
                var This = this;
                return function( n1, n2 ) {
                    return This.bInt ? Math.floor(Math.random()*(n2 - n1) + n1) : Math.random()*(n2 - n1) + n1
                };
            }
        };
    });
    m1.controller(‘firstController‘, [‘$scope‘, ‘randomFn‘, function($scope, randomFn) {
        console.log( randomFn(0, 5) );
    }]);
    </script>
</head>
<body ng-controller="firstController">
    
</body>
</html>
angularJs 自定义服务 provide 与 factory 的区别
原文:http://www.cnblogs.com/zsongs/p/5585887.html