Shalini
Shalini

Reputation: 51

Does parent controller get re-initialized again while navigating between child tabs?

I have a parent controller and two tabs within it, each having its own controller as shown in image below: Parent and Child View Model

I am broadcasting an event from Tab1/Tab2 controllers using $rootScope and catching it directive's controller scope using $scope. When I am switching between tabs, the parent controller and the directive's controller are getting initialized again and the event is caught twice in directive's controller even though it is broadcasted just once. I tried to debug and noticed the directive's controller $id when it was being caught. When the event was caught first time, the directive's id was the one which got created with previous tab(tab from which i switched). And second time, directive's id was the one which got created with current tab (tab to which i switched).

Note: 1) Even after using reload: false option, parent controller and directive controller is getting re-initialized. 2) I am not initializing parent controller by using ng-controller in html. It is getting initialized only via $stateProvider routing.

This is how i configured my states:

$stateProvider
  .state('app.parent', {
    url: 'parent/:paramId',
    params: {
      paramId: 'sample'
    },
    views: {
      'content-parent@app': {
        templateUrl: 'parent.html',
        controller: 'ParentController',
        resolve: {
          defaultParams: function(parentService, $stateParams) {
            return parentService.getDefaultParams($stateParams.paramId);
          }
        }
      }
    }
  })
  .state('app.parent.tab1', {
    url: '/tab1/',
    views: {
      '[email protected]': {
        templateUrl: 'tab1.html',
        controller: 'Tab1Controller'
      }
    }
  })

  .state('app.parent.tab2', {
    url: '/tab2/',        
    views: {
      '[email protected]': {
        templateUrl: 'tab2.html',
        controller: 'Tab2Controller'
      }
    }
  });

Upvotes: 2

Views: 72

Answers (2)

PaulD
PaulD

Reputation: 1

The parent State remains unchanged as long as you do not push the changes to the parent controller using emit.

Here is a c-sharpcorner link that might help you!

Upvotes: 0

Nikolaj Dam Larsen
Nikolaj Dam Larsen

Reputation: 5674

No, the parent state (and thus controller/component) is not re-initialized when the child states are changed. This includes any resolve functions and state event handlers associated with the parent state.

Here's a Plunker that illustrates that the parent scope remains the same when you navigate between child states.

You can force it to reload the parent though, by setting the reload option of $state.go(..) to true. Like this:

$state.go('parent.childA', null, { reload: true });

Upvotes: 0

Related Questions