Mitesh Sharma
Mitesh Sharma

Reputation: 261

How to change only child ui-view while keeping parent as same in ui-router angularjs?

I have a ui-view inside index.html.

Inside this ui-view, i have added child ui-view="child1" which is working fine using $stateProvider state with nested views. Now on tab switch i want to change only child ui-view which is named "child1", but keeping parent ui-view as same (as i am on same page, just part of page is changing).

Is there any way we can achieve using routes? I also want to change url parameter so that on refresh I know which tab was open, so that i can open same tab using routes.

$stateProvider
    .state('main', {
      url: '/',
      views: {
        '': {
          templateUrl: 'assets/views/main.html',
          controller: 'mainInitCtrl',
        },
       'child1': {
          templateUrl: 'assets/views/child1.html',
          controller: 'childInitCtrl',
        }
      }
    });

Upvotes: 1

Views: 2174

Answers (1)

Radim Köhler
Radim Köhler

Reputation: 123891

You should try to use not only nested views, but also nested states. So each tab will trigger child state. That way, parents view (unnamed) will stay unchanged all time, while child views will be changing with each tab click

// parent state main
.state('main', {
  url: '/',
  views: {
    '': {
      templateUrl: 'assets/views/main.html',
      controller: 'mainInitCtrl',
    },
  }
});
// select a tab1 and go to main.tab1 state
// parent view will stay, and "child1" view in index.html 
// will be replaced with content below
.state('main.tab1', {
  url: '/tab1',
   'child1@': {
      ...
    }
  }
})
// another tab
.state('main.tab2', {
  url: '/tab2',
   'child1@': {
      ...
    }
  }
})

similar Q & A with working plunker

Angular ui-router... Display default tab

But in case, that we want to have ui-view="child1" to be inside of the unnamed ui-view - we just have to move into parent 'main' state template

assets/views/main.html:

<div>
  main content
  ...
  <div ui-view="child1"></div>
</div>

This make more sense, and will fit to most scenarios. But child states definition now have to target parent 'main' not index.html, like this:

.state('main.tab1', {
  url: '/tab1',
   //'child1@': {
   'child1': {
      ...
    }
  }
})
// another tab
.state('main.tab2', {
  url: '/tab2',
   //'child1@': {
   'child1': {
      ...
    }
  }
})

Upvotes: 1

Related Questions