provider and $provide.decorator

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="../lib/AngularJs/angular.min.js"></script>
    <script src="../lib/AngularJs/ui-router.js"></script>
</head>
<body>
    <div data-ng-app="myApp" data-ng-controller="myCtrl">
        <h1>home</h1>
    </div>
</body>
<script>
    var myApp = angular.module('myApp',['ui.router']);
    myApp.provider('foo',function(){
        var thisIsPrivate = 'private';
        return {
            setPrivate:function(newVal){
                thisIsPrivate = newVal;
            },
            //$get才是公开给用户的 ,其他的可在config里面使用
            $get:function(){
                function getPrivate(){
                    return thisIsPrivate;
                }
                return {
                    variable:'public',
                    getPrivate:getPrivate
                };
            }
        };
    });

    //config用name + Provider , 用户用name
//    myApp.config(function(fooProvider){
//        fooProvider.setPrivate('new value');
//    });
    //添加新属性
    myApp.config(function($provide){
        $provide.decorator('foo',function($delegate){
            $delegate.greet = function(){
                return 'hello world';
            };
            return $delegate;//记得return
        });
    });
    myApp.controller('myCtrl',['$scope','foo',function($scope,foo){
        $scope.name = 'Jackey';
        //console.log(myService.getName());
        console.log(foo.getPrivate());

    }]);
</script>
</html>
原文地址:https://www.cnblogs.com/lihaozhou/p/4096248.html