zipper
zipper

Reputation: 397

ui-router: parent view disappeared when $state.go to child state

I'm trying to dynamically create a navigation tree for my left-side nav-panel by recursively creating states for each nav-node (the navigation data is reading from the server's DB).

The template:

<script type="text/ng-template" id="navTree">
  <ul class="nav flex-sm-column">
    <li ng-repeat="node in $ctrl.nodeList">
      <div ng-click="$ctrl.newState(node)">
        <span class="{{node.class}}"></span>&nbsp;{{node.title}}
      </div>
      <div ng-if="node.children.length > 0" ui-view>
      </div>
    </li>
  </ul>
</script>

Ignoring the fetching data and initiating navPanel code, bellow is the navTree state definition code:

let st_navTree = {
  name: 'navTree',
  params: {
    nodeList: []
  },
  controller: ['$transition$', 'runtimeStates', '$state', function ($transition$, runtimeStates, $state) {
    ctrl = this;
    ctrl.nodeList = $transition$.params().nodeList;
    ctrl.newState = function (node) {
      let subStateName = $state.current.name + '.' + node.name;
      runtimeStates.newState(subStateName, st_navTree);
      $state.go(subStateName, {nodeList: node.children});
    };
  }],
  controllerAs: '$ctrl',
  templateUrl: 'navTree'
};

The code that dynamically generating new states (learning from here):

app.provider('runtimeStates', ['$stateProvider', function ($stateProvider) {
  this.$get = function () {
    return {
      newState: function (name, state) {
        $stateProvider.state(name, state);
      }
    };
  };
}]);

The immediate problem is (other problems like re-creating states need to be solved lately):

Although I can see the top level nav-list in the nav-panel; but when I go into the sub menu by clicking an nav-node, instead of adding a sub-view under the parent view, the whole nav-panel's content changes to the sub-state's view, and all parent level views are gone.

I saw another thread and in the comments "this does not work if you change the states with $state.go or $state.transitionTo. Works fine with ui-sref." I worry that $state.go cannot go to the child-state with the parent-view remains.

I'm thinking to change it to ui-sref version, but the dynamic routing will be a new problem which I still have no idea.

Upvotes: 0

Views: 288

Answers (1)

shaunhusain
shaunhusain

Reputation: 19748

This is an atypical use case for sure... typically if the thing in the URL is dynamic I would be treating it as a query/state parameter but if you really want to have the URLs be dynamically generated it appears this is now baked into the newer versions of UI-Router or available in the ui-router extras as explained here:

Angular - UI Router - programmatically add states

https://ui-router.github.io/ng1/docs/latest/modules/injectables.html#_stateregistry

Upvotes: 0

Related Questions