gpt4 book ai didi

angularjs - 当您只能访问模块变量时注入(inject)模块

转载 作者:行者123 更新时间:2023-12-04 23:55:21 25 4
gpt4 key购买 nike

假设你有一个

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

现在您需要向该模块注入(inject)其他内容,但您无法更改该行,您只能访问 app多变的。

所以这行不通,对吧?
var mod2 = angular.module('mod2',[]).factory('$myService', function(){ 
return { do: function(){alert('doing'); }
})

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

当然,您总是可以这样做:
injector = angular.injector(['mod2'])
$myService = injector.get('$myService')

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

最佳答案

这取决于您的代码何时实际运行。
我试过this plunker它奏效了。

应用程序.js

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

我的模块.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;
}]);

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

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

关于angularjs - 当您只能访问模块变量时注入(inject)模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17284577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com