当您只能访问模块变量时注入模块 [英] injecting module when you have access only to a module variable

查看:51
本文介绍了当您只能访问模块变量时注入模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个

var app = angular.module('Mod1',[])

现在您需要向该模块注入其他内容,但是您无法更改该行,只能访问app变量.

and now you need to inject something else to that module, but you can't change that line, you only have access to the app variable.

所以这行不通,对吧?

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

app.directive('foo',[$myService]) // $myService here is undefined

您当然可以随时这样做:

Of course you can always do:

injector = angular.injector(['mod2'])
$myService = injector.get('$myService')

尽管我想知道是否还有更优雅的解决方案

Although I'm wondering if there's more elegant solution

推荐答案

这取决于您的代码何时实际运行. 我尝试了这个小酒杯,它奏效了.

It depends on when is your code actually run. I tried this plunker and it worked.

app.js

var app = angular.module('plunker', []);

myModule.js

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;
}]);

index.html

index.html

<head>
  <script src="app.js"></script>
  <script src="myModule.js"></script>
</head>

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

You need to add your extra modules after the app.js is loaded but within the same javascript execution sequence. Timeouts and async loading failed for me.

这篇关于当您只能访问模块变量时注入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆