Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

angularjs - Angular UI Router - Dynamic TemplateURL

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...