问题
Well, I need some help about a routing problem with Angular UI-Roter. Well, actually is not a problem, it's more about to reduce code.
I have three child states:
- main.tab1.hello
- main.tab2.hello
- main.tab3.hello
and they have in common the same 'templateUrl'
: 'hello.html'
I want to know if is possible to reduce them in only one state, and of course, when I click the button, I don't want to change the URL.
Here is my Plunkr: http://plnkr.co/edit/ej7pCo1RRXPTBL6p8dsL
Any help would be appreciated.
回答1:
...Well, actually is not a problem, it's more about to reduce code.
In general, I would suggest to use some array
of state names and just iterate that to create all its children:
var states = ["main.tab1", "main.tab2", "main.tab3"]
states.forEach(function(parentName){
$stateProvider
.state(parentName + ".hello", {
views: {
"viewC@main": {
templateUrl:"hello.html"
}
},
})
})
There is the updated plunker with that approach in place
But there are even more sophisticated approaches, profiting from built in feature:
decorator(name, func)
There are working examples with detailed explanation:
- How to decorate current state resolve function in UI-Router? Current function isn't invoked
- AngularJS: How to set one state as a global parent in UI-Router (to use modal as common parts)
回答2:
The easiest way would be to define your state object, and then simple re-use it when registering the states:
var helloState = {
views: {
"viewC@main": {
templateUrl:"hello.html"
}
},
};
$stateProvider
//snip...
.state("main.tab1.hello", helloState)
.state("main.tab2.hello", helloState)
.state("main.tab3.hello", helloState);
Taking it one step further you could define a service that exposes all of these state definitions. If you need to override any properties you can use angular.extend
on the state object.
来源:https://stackoverflow.com/questions/33107986/how-to-reduce-number-of-states-with-same-templateurl-using-angular-ui-router