当您只能访问模块变量时注入模块

iLe*_*ing 4 angularjs

假设你有一个

var app = angular.module('Mod1',[])
Run Code Online (Sandbox Code Playgroud)

现在你需要向该模块注入其他东西,但你不能改变那一行,你只能访问该app变量.

所以这不起作用吧?

var mod2 = angular.module('mod2',[]).factory('$myService', function(){ 
       return { do: function(){alert('doing'); }
})

app.directive('foo',[$myService]) // $myService here is undefined
Run Code Online (Sandbox Code Playgroud)

你当然可以做到:

injector = angular.injector(['mod2'])
$myService = injector.get('$myService')
Run Code Online (Sandbox Code Playgroud)

虽然我想知道是否有更优雅的解决方案

Liv*_* T. 7

这取决于您的代码实际运行的时间.我尝试了这个plunker它工作.

app.js

var app = angular.module('plunker', []);
Run Code Online (Sandbox Code Playgroud)

myModule.js

var myModule = angular.module('myModule', []);
myModule.service('MyService', function() {
  return {test: 'MyService'};
});

app.requires.push('myModule');

app.controller('MainCtrl', ['$scope','MyService', function($scope, MyService) {
  $scope.name = MyService.test;
}]);
Run Code Online (Sandbox Code Playgroud)

的index.html

<head>
  <script src="app.js"></script>
  <script src="myModule.js"></script>
</head>
Run Code Online (Sandbox Code Playgroud)

您需要在加载app.js之后添加额外的模块,但是在相同的javascript执行序列中.超时和异步加载失败了.