sharing between modules with AngularJS?

前端 未结 1 2006
情书的邮戳
情书的邮戳 2020-12-31 12:44

Let\'s say I have a stuff module that I want to inject into myApp config:

angular.module(\'myApp\', [\'stuff\']).
  config([functio         


        
相关标签:
1条回答
  • 2020-12-31 12:56

    Inject a module into both that shares these properties.

    Use the provider class to overwrite properties or instantiate them from any scope:

    angular.module("stuff.things", []).provider("$things", function(){
        var globalOptions = {};
        this.options = function(value){
            globalOptions = value;
        };
        this.$get = [, function () {
            function Things(opts) { 
                var self = this, options = this.options = angular.extend({}, globalOptions, opts);
            }
            Things.prototype.returnOptions = function(){
                return this.options;
            };
            return {
                things: function(opts){
                    return new Things(opts);
                }
            };
        }];
    });
    

    The secret sauce: $things.things().returnOptions()

    angular.module('stuff.thing1', ['stuff.things']).provider("$thing1", function(){
        var globalOptions = {};
        this.options = function(value){
            globalOptions = value;
        };
    
        this.$get = ['$things', function ($things) {
            function Thing1(opts) {
                var self = this, options = this.options = angular.extend({}, $things.things().returnOptions(), globalOptions, opts);
            ...
            }
            return {
                thing1: function(opts){
                    return new Thing1(opts);
                }
            };
        }];
    });
    
    0 讨论(0)
提交回复
热议问题