我想使用 ui-router 和 AngularJS 将 $stateParams 注入(inject)到一个非匿名函数中。
使用匿名函数,我通常会这样做:
.state('app.users', {
url: '/users/:param1/:param2',
params: {
...
},
templateUrl: function($stateParams) { // <----- Here is the anonymous function
... do something ...
},
resolve: {
...
}
})
我想要做的是将函数($stateParams)替换为我之前设置的函数。像这样的东西:
// Here is my function being set before the code,
// so I can use the same function in multiple states without duplicating code
var myFunction = function (myParam, $stateParams) {
... do something ...
}
... setting the routes on ui-router ...
.state('app.users', {
...
templateUrl: myFunction(myParam, $stateParams), // <--- I want to set that function here, injecting the "$stateParams" at the same time
...
}
我想到了一种方法来解决这个问题:创建一个匿名函数,然后在该匿名函数中我可以调用 myFunction
并注入(inject) $stateParams 。但感觉不对。
我的问题是:
$stateParams 如何注入(inject)到匿名函数中?有什么方法可以将其注入(inject) myFunction
而不创建另一个匿名函数吗?
最佳答案
这样做是适当的
templateUrl: myFunction,
Angular 使用 $injector.invoke或$injector.instantiate对于依赖注入(inject)(在本例中是前者),两者都使用 $injector.annotate在内部找出应该注入(inject)哪些依赖项。 $injector.annotate
parses使用正则表达式对被调用函数进行签名并获取依赖项名称。
还需要提供annotation for myFunction
以便在缩小的 JS 中正确注释它。
关于javascript - AngularJS,ui-路由器: Inject $stateParams into NOT anonymous function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33964642/