重用需要 `resolve`d 参数的 `ui-route` 控制器 [英] Reuse `ui-route` controller that expects a `resolve`d parameter
问题描述
我希望能够重用我的 ui-router
有线控制器.他们目前从 ui-router
resolve
接收参数来渲染他们的模板.我可以在没有 ui-router
的情况下重用这些控制器吗?
I want to be able to reuse my ui-router
-wired controllers. They currently receive parameters from ui-router
resolve
to render their templates. Can I reuse those controllers without ui-router
?
例如,我使用 ui-router
执行此操作:
For example, I do this with ui-router
:
.controller('DetailController', function ($scope, detailData) {
$scope.controllerDetail = detailData + "is awesome!";
})
.config(function ($stateprovider) {
$stateprovider.state('detailState', {
resolve: {
detailData: function () { return "John Doe"; }
},
template: '<p>{{ controllerDetail }}</p>',
controller: 'DetailController'
}
}
现在,我想使用相同的控制器在别处渲染固定的子面板.例如:
Now, I want to use the same controller to render a fixed sub-panel elsewhere. For example:
<master ng-init='childData="Jane Smith"'>
<detail ng-controller='DetailController' ng-controller-params="{ detailData : childData">
<p>{{ controllerDetail }}</p>
</detail>
</master>
当然,在实践中,实际上有模板文件,并且控制器中的一些功能值得去重复.此外,第一个示例中的 resolve
数据和第二个示例中的 init
数据都通过网络到达,但在第二个示例中,它作为更大的子对象到达请求而不是单独导航的项目.此外,我在指令中而不是通过 HTML 属性分配我的控制器.
Of course, in practice, there are actually template files, and some functionality in the controller worth de-duplicating. Also, the resolve
data in the first example and init
data in the second example both arrive over the wire, but in the second example it arrives as a child object of a larger request rather than an individually-navigated item. Also, I assign my controllers in directives rather via HTML attributes.
推荐答案
就我而言,这是一个类似但有限的子案例,我有多个带有 resolve() 的
已定义,并且只有一处,控制器通过ui-router
路由ng-controller
在模板中实例化,并将值传递给控制器在这种情况下是一个已知的恒定值.
In my case, which is a similar though limited subcase, I had multiple ui-router
routes with resolve()
defined, and only one place with the controller instantiated in a template via ng-controller
, and the value passed to the controller in such case was a known, constant value.
在这种情况下,你可以简单地做
In such case, you can simply do
.value('detailData', 'here goes the default/fallback value')
如果你多次使用ng-controller
,应该有不同的detailData
,你显然需要找到更好的解决方案.
If you have multiple usages of ng-controller
which should have different detailData
, you need to find a better solution obviously.
这篇关于重用需要 `resolve`d 参数的 `ui-route` 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!