简体   繁体   中英

Ui-router parent state, child states controllers

I'm trying to create a parent state which should go to a childstate by default. I need to be able to have a parentController and ChildControllers. I tried the following but as you can see my childControllers are not called.

var app = angular.module('test', ['ui.router']);

app.config(config);

app.controller('ParentCtrl', ['$scope', function ($scope) {
    console.log('parentCtrl');
}]);

app.controller('Child1Ctrl', ['$scope', function ($scope) {
    console.log('Child1Ctrl');
}]);

app.controller('Child2Ctrl', ['$scope', function ($scope) {
    console.log('Child2Ctrl');
}]);

states:

function config($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/parent');

    $stateProvider.state('parent', {
        abstract: true,
        views: {
            'main': {
                controller: 'ParentCtrl',
                controllerAs: 'parentCtrl',
                templateUrl: 'page.html'
            }
        },
        url: '/parent/'
    });
    $stateProvider.state('parent.child1', {
        views: {
            'main': {
                controller: 'Child1Ctrl',
                controllerAs: 'child1Ctrl',
                templateUrl: 'page.html'
            }
        },
        url: 'child1?param1',
    });
    $stateProvider.state('parent.child2', {
        views: {
            'main': {
                controller: 'Child2Ctrl',
                controllerAs: 'child2Ctrl',
                templateUrl: 'page.html'
            }
        },
        url: 'child2?param2', //is this /parent/child2... ?
    });
}

You can also find the code here: https://jsfiddle.net/vjgh8ntL/2/

Can someone guide me in the right direction?

I would use in this case just different otherwise:

$urlRouterProvider.otherwise('/parent/child1?child1=null');

Check this working example

There are similar Q & A (with even different solutions, eg .when() setting) :

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