AngularJS UI-Router parent

Issue

I’m using UI-Router for a project of mine and I just noticed that when I reload a child state the controller for the parent also runs (again) along with the child controller. The scope from the parent gets inherited by the child. Is this supposed to work like this? Can I isolate the child scope?

I need the parent/child relation to get breadcrumbs to work.

app.config(function($stateProvider, $urlRouterProvider) {
	$stateProvider
	.state('parent', {
		name: 'parent',
		url: '/parent',
		templateUrl: 'parent-template.html',
		controller: 'parentController',  		
	})
	.state('child', {
		name: 'child',
		parent: 'parent',
		url: '/child',
		templateUrl: 'child-template.html',
		controller: 'childController',
	})
	.state('orphan', {
		name: 'orphan',
		url: '/orphan',
		templateUrl: 'orphan-template.html',
		controller: 'orphanController',
	});
	// if no route is matching
	$urlRouterProvider.otherwise('/parent');
});
<!-- INDEX.HTML -->
<body>
    <div ng-app="app">
      <main role="main" class="container">
        <div ng-app="app">
          <ui-view></ui-view>
        </div>
      </main>
    </div>
</body

<!-- PARENT-TEMPLATE.HTML -->
<ui-view>
	<div class="container">
		parent content
	</div>
</ui-view>

<!-- CHILD-TEMPLATE.HTML -->
<ui-view>
	<div class="container">
		child content
	</div>
</ui-view>

<!-- ORPHAN-TEMPLATE.HTML -->
<div class="container">
	Orphan Content
</div>

Solution

The controller are instantiated because the view is showing. Try to use named views: https://github.com/angular-ui/ui-router/wiki/Multiple-Named-Views

The UI-ROuter are a powerfull tool with a huge great options but “great power comes great responsibility” on my own experience all its options got me lost lot of time, to test and understand. Finally the best (but not the easeast) is try to use it as simple as posible.

Answered By – pdorgambide

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.