paj28
paj28

Reputation: 2320

Can I make my angular-ui-router stateProvider definition shorter?

I am using angular-ui-router, which is generally great, but my code to define the stateProvider is becoming quite repetitive, e.g.

.state('home', {
  url: "/home",
  templateUrl: "home.html"
})
.state('products', {
  url: "/products",
  templateUrl: "products.html"
})
.state('suppliers', {
  url: "/suppliers",
  templateUrl: "suppliers.html"
})

Is there some way to tell it that every state has a URL and template that matches the state name?

Upvotes: 1

Views: 436

Answers (1)

Alp
Alp

Reputation: 29739

Write a function.

var myState = function($stateProvider, name) {
    $stateProvider.state(name, {
        url: '/' + name,
        templateUrl: name + '.html'
    })
}

Then you can use it like so:

myState($stateProvider, 'home');
myState($stateProvider, 'products');
myState($stateProvider, 'suppliers');

If you like you can also extend the $stateProvider object:

$stateProvider.myState = function(name) {
    return this.state(name, {
        url: '/' + name,
        templateUrl: name + '.html'
    })
}

Use it like this:

$stateProvider
    .myState('home')
    .myState('products')
    .myState('suppliers');

Upvotes: 4

Related Questions