Search code examples
angularjsangularjs-routing

dynamic template based on $routeProvider resolves


I've got a url in my application that needs to load one of two templates based on the results of a resolve call, like so:

app.config(function($routeProvider) {
    $routeProvider.
        when('/someurl', {
            resolve: {
                someData: function(dataService) {
                    var data = dataService.loadData();

                    // data has a .type field that determines which template should be loaded

                    return data;
                }
            },
            templateUrl: function(routeParams) {
                // return a path based on the value of data.type in the someData resolve block
            }
        })
});

Is there a way for me to set the templateUrl based on what's returned by the someData resolve?


Solution

  • So I figured out how to do this using ui-router - thanks m59 for pointing me at it.

    Here's how you'd do this with ui-router:

    app.config(function($stateProvider) {
        $stateProvider
            .state('someState'
                url: '/someurl',
                template: '<ui-view>',
                resolve: {
                    someData: function(dataService) {
                        var data = dataService.loadData();
    
                        // data has a .type field that determines which template should be loaded
    
                        return data;
                    }
                },
                controller: function($state, someData) {
                    $state.go('someState.' + someData.type);
                }
            })
            .state('someState.type1', {
                templateUrl: 'someTemplate1.html',
                controller: 'Type1Controller'
            })
            .state('someState.type2', {
                templateUrl: 'someTemplate2.html',
                controller: 'Type2Controller'
            })
    });
    

    There's a parent state that handles resolves, then redirects to the child states based on the information it gets. The child states don't have a url, so they can't be loaded directly.