我有一個服務和控制器的大列表,當網站第一次加載時創建,然後我調用angular.bootstrap。然後,後來我想運行一些可以依賴注入的任意代碼。我這樣做的方式是創建一個函數,用註釋指定它的依賴關係,獲取我正在使用的模塊的注入器,然後調用該函數的invoke。angularjs:invoke創建新的服務
我使用requirejs來加載這個插件和任何其他插件,以便返回模塊的內容。代碼如下所示
define [
'scripts/inherits/basePlugin'
] , (BasePlugin) ->
# The explicit block lists the angular services/factories you need
# all game logic/entity classes go inside this block
explicit = (Options, Renderer) ->
class Checkers extends BasePlugin.Plugin
constructor:() ->
super()
@checkersOptions = [
[
"checkbox",
"test checkbox",
false
],
[
"slider",
"test slider",
0, 3, 1
],
[
"textbox",
"test textbox",
"this is some text"
],
[
"dropdown",
"test dropdown",
["blah", "blah2", "blah3"],
"blah2"
]
]
Options.addPage "Checkers", @checkersOptions
selectEntities: (renderer, turn, x, y) ->
verifyEntities:(renderer, turn, selection) ->
getName:() -> 'Checkers'
predraw: (turn, dt, renderer) ->
postdraw: (turn, dt, renderer) ->
resize: (renderer) ->
loadGame: (@gamedata, renderer) ->
getSexpScheme:() -> null
return Checkers
# the dependencies are manually injected here
explicit.$inject = ['Options', 'Renderer']
$injector = angular.injector(['webvisApp'])
# the constructor function for the main checkers object is returned here
return $injector.invoke(explicit)
現在到了最後,我試圖返回類原型「跳棋」這裏訪問的角度服務「選項」和「渲染」。最後,當我調用invoke時,它會毫無怨言地運行,但由於某種原因,這兩個服務會被重新實例化,因爲這兩個服務的構造函數會被再次調用,從而消除以前的任何數據。爲什麼invoke會導致這些服務被重新創建?
編輯: 解答:發現注射器功能創建新的注射器,而不是使用模塊中的注射器。我的解決辦法是這樣的:
# make your module
webvisApp = angular.module 'webvisApp', [
'ngCookies'
'ngSanitize'
'ngRoute'
'ui.bootstrap'
]
# attach injector to publicly accessible member
webvisApp.run ($injector) ->
webvisApp.injector = $injector
# create your controllers and services
# bootstrap the application
angular.bootstrap document, ['webvisApp']
然後調用與依賴一些功能:
needsDependencies = (Renderer, Options) ->
#do stuff
needsDependencies.$inject = ['Renderer', 'Options']
webvisApp = angular.module('webvisApp')
webvisApp.injector.invoke needsDependencies
就是這樣。不太明白製作這種新噴射器的用例是什麼,但無論如何。在模塊的運行模塊中,在引導和所有提供程序生成後,我將$注入器附加到模塊上,如webvisApp.injector = $ injector。然後我能夠注入像webvisApp.injector.invoke funcName這樣的abritrary函數。像魅力一樣工作。謝謝! – FatalCatharsis