How to reference values with the same name from different modules

后端 未结 2 1388
别那么骄傲
别那么骄傲 2021-02-13 16:05

If I have some modules which defines the same value object:

var m1 = angular.module(\'m1\', []);
m1.value(\'test\', \'AAA\');

var m2 = angular.modu         


        
2条回答
  •  离开以前
    2021-02-13 16:26

    Actually, you can (sort of) do this, but it requires a bit more manual work. See this plunkr.

    var foo = angular.module('foo', ['ng']).value('test', 1);
    var bar = angular.module('bar', ['foo']).value('test', 2);
    console.log(angular.injector(['foo']).get('test')); // 1
    bar.service('original', ['test', function(test) {
        console.log(test); // 2
    }]);
    

    As the other answers stated, the module namespace is global so the controller in 'foo' gets the Test value from 'bar'. However, by using angular.injector([...modules]) we can explicitly retrieve values/services/whatnot from certain modules.

    Of course this doesn't natively work with Angular's DI system, but personally that doesn't really bother me since function(Foo) {} or function() { Foo = angular.injector(['myModule']).get('Foo'); } is slightly more typing, but not necessarily worse (we're still injecting something, only manually).

    Also, directives and filters would need to be made unique in another way, but it gives a starting point.

提交回复
热议问题