简体   繁体   中英

Angular ui-router not calling child controller in nested routes

I have my routes set up as below. Its too frustrating that the view in view.tab is loaded but its controller isn't called. I tried without the paramaters, but it still doesn't work as expected. Does anyone have any idea on how to solve this?

    $stateProvider
    .state('index', {
        url: '/',
        templateUrl: viewsRoot + 'restaurants/index.htm',
        controller: 'RestaurantsCtrl'
    })
    .state('view', {
        url: '/view',
        controller: 'RestaurantsViewCtrl',
        templateUrl: viewsRoot + '/restaurants/view.htm'
    })
    .state('view.tab', {
        url: '/orders',
        // controller: 'OrdersIndexCtrl',
        controller: function ($scope) {
            alert('This does not run');
        },
        views: {
            "view": {
                templateUrl: viewsRoot + '/restaurants/orders.htm'
            }
        }
    });

$urlRouterProvider.otherwise("/");

You need to declare the controller along side the template:

views: {
            "view": {
                templateUrl: viewsRoot + '/restaurants/orders.htm',
                controller: 'MyController' // (or a function, etc.)
        }

The UI-Router wiki sort of alludes to this:

If you define a views object, your state's templateUrl, template and templateProvider will be ignored. So in the case that you need a parent layout of these views, you can define an abstract state that contains a template, and a child state under the layout state that contains the 'views' object.

Controllers are paired with a view. So if it ignores the "template" properties defined on the state, it seems to imply that it will ignore the controller too.

If you want all of your named views to share a controller, define an abstract parent state as the wiki suggests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM