Harish Paudel Harish Paudel - 3 months ago 12
AngularJS Question

AngularJS: Construct ui-states from array of template strings

I have static template files (around 50) and I would like to construct ui-states from these template array

var templates = ['index.html','about.html','contact.html','careers.html']


and my state would simply go like this :

$stateProvider
.state('index',{url:'/index.html',templateUrl:'templates/index.html'})
.state('about',{url:'/about.html',templateUrl:'templates/about.html'})
.state('contact',{url:'/contact.html',templateUrl:'templates/contact.html'})


Can I achieve like this?

templates.forEach(function(template){
$stateProvider.state(template,{url:'/'+template,templateUrl:'templates/'+template})
})

Answer

simply forEach through your templates and create a state per each template

var templates = [
      'index.html',
      'about.html',
      'contact.html'
    ];

    templates.forEach(function(tmp){
      $stateProvider
        .state(tmp,{
          url:'/'+tmp,
          templateUrl:tmp
        })
    })