How to reduce number of 'states' with same 'templateUrl' using Angular Ui-Router

白昼怎懂夜的黑 提交于 2019-12-11 12:34:26

问题


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:

  1. main.tab1.hello
  2. main.tab2.hello
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!