AngularJS、ui-路由器:将 $stateParams 注入非匿名函数

AngularJS, ui-router: Inject $stateParams into NOT anonymous function

我想使用 ui-router 和 AngularJS 将 $stateParams 注入到一个非匿名函数中。

使用匿名函数,我通常会这样做:

.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 并注入 $stateParams。但这感觉不对。

我的问题是: $stateParams 如何注入匿名函数?有什么方法可以在不创建另一个匿名函数的情况下将其注入 myFunction 吗?

做的合适

 templateUrl: myFunction,

Angular 使用 $injector.invoke or $injector.instantiate for dependency injection (it is the former in this case), both use $injector.annotate internally to figure out what dependencies should be injected. $injector.annotate parses 带有正则表达式的被调用函数的签名并获取依赖项的名称。

还需要为 myFunction 提供 annotation 以便在缩小的 JS 中正确注释。