Angular-UI ui-router supporting infinitely nested states

I have a situation in my Angular application where I would like to consider an infinitely nested state / route. For example, let's say that I have a person, and I want to see the family tree. I can have routes that look like this:

/person/0
/person/0/child/1
/person/0/child/1/child/2
/person/0/child/1/child/2/child/3

And this can go on forever, as the user clicks further down the tree. How is such a route determined by ui-router?

+4
source share
1 answer

You can use a regex to determine your route, and then parse the URL to get a child identifier, for example:

$stateProvider.state('person', {
    url: '/person/:id',
    views: {
        '': {
            templateUrl: 'parentTemplate.html',
            controller: 'ParentCtrl'
        }
    }
}).state('child', {
    url: '/person/:id/{path:.*}',
    templateUrl: function(params) {
        // params.path contains something like `child/1/child/2`
        // so you get get the current child id like this
        var path = params.path.split('/').reverse(),
            childId = path[0];
        // for more flexibility you can retrieve all ids from the request and store them in $stateParams
        // so you can easily work with them in your controller

        // here you can write some logic to determine the right template
        return 'childTemplate.html';
    },
    controller: 'ChildCtrl'
});
0
source

Source: https://habr.com/ru/post/1537124/


All Articles