Reuse `ui-route` controller that expects a `resolve`d parameter

拈花ヽ惹草 提交于 2019-12-10 21:37:30

问题


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?

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>

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.


回答1:


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')

If you have multiple usages of ng-controller which should have different detailData, you need to find a better solution obviously.



来源:https://stackoverflow.com/questions/29023440/reuse-ui-route-controller-that-expects-a-resolved-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!