ch3my ch3my - 6 months ago 11
AngularJS Question

Dynamic variable in URL in AngularJS

I have an Angular app which has several dynamic fields, each of these fields are changed updated based on config which comes from a backend database.

In order to control what config is used I need to dynamically switch a single variable - I've decided that the URL is the best way to set/switch the variable as there need to be multiple permutations of the site based on the URL so:-

/:dynamicVariable/


I'm looking for some guidance as to whether this is the best way to do it and what the best way to do it would be? I'm struggling as I don't want to have to set each route for each section like this
/:dynamicVariable/homepage
/:dynamicVariable/about-us
etc etc. Ideally the core module checks it and sets it but the routing ignores it so
/:dynamicVariable/
becomes the root.

Hope that makes sense, thanks in advance for your help.

Answer

I ended up doing this by using ui.router and nesting states within an abstract parent state which held the client, like so :-

.state('rootClient', {
            abstract: true,
            url: '/:client',
            templateUrl: 'app/layout/layout.html',
            controller: 'Layout',
            controllerAs: 'layout',
            noClient: false,
            resolve: {
                client: function ($stateParams, ClientService) {
                    return ClientService.getClient($stateParams.client);
                }
            }
        })
.state('rootClient.home', {
            url: '/homepage',
            views: {
                'content': {
                    templateUrl: 'app/homepage/homepage.html',
                    controller: 'Homepage',
                    controllerAs: 'home'
                }

            }

        });

This way all the routes are under the parent route, I also added a resolve to make sure the client exists before moving to the route. Hopefully this will help someone else down the line.

Cheers