3

I am building a static HTML website with angular UI router for navigation. I basically have one ui-view with multiple (10+) html templates (pages) to load into that view. All my template pages are in a directory called 'pages'.

So i basically want to know if we can define just one state in the $stateProvider to assign multiple template urls dynamically instead of writing different states for each HTML template page (like mentioned below).

$stateProvider
.state('home', {
    url: '/home',
    templateUrl: 'pages/home.html',
    controller: 'homeController',
    controllerAs: 'home'
})
.state('viz', {
    url: '/viz',
    templateUrl: 'pages/viz.html',
    controller: 'vizController',
    controllerAs: 'viz'
})
.state('about', {
    url: '/about',
    templateUrl: 'pages/about.html',
    controller: 'aboutController',
    controllerAs: 'about'
})....

Any help is much appreciated.

1
  • You can, but you will be stepping away from the whole point of ui-router. The back button won't work, it isn't as scalable etc. If you want to do it this way you could just use nginclude. Commented Nov 16, 2015 at 13:05

1 Answer 1

9

That should not be so difficult, check for example this:

Angular UI-Router dynamic routing based on slug from API Ajax Call. Load view based on slug

We can use $stateParams and templateProvider to

.state('general', {
   url: '/{type}',
   //templateUrl: 'pages/home.html',
   templateProvider: ['$stateParams', '$templateRequest',
      function($stateParams, $templateRequest) 
      {
        var tplName = "pages/" + $stateParams.type + ".html";
        return $templateRequest(tplName);
      }
    ],
    // general controller instead of home
    //controller: 'homeController',
    controller: 'generalController',
    controllerAs: 'ctrl'

We can also restrict the parameter type to be just one of the expected values, see:

url: '/{type:(?:home|viz|about)}',

Angular js - route-ui add default parmeter

There is also very similar Q & A with working plunker and more details:

AngularJS ui-router - two identical route groups

Another examples could be found here:

Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what i was looking for. Cheers.
Great to see that, sir ;) Enjoy mighty UI-Router!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.