How to reference values with the same name from different modules

后端 未结 2 1399
别那么骄傲
别那么骄傲 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.

    0 讨论(0)
  • 2021-02-13 16:47

    In short - no. AngularJS modules form one namespace. If you define 2 values with the same name on 2 different modules only one will be visible during runtime. This applies to any providers, not only values.

    This might get addressed in future versions of AngularJS but for now your best option is to prefix your values (and other providers) with a module name.

    0 讨论(0)
提交回复
热议问题