1

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>

1
  • I realized that this is AngularJS scope inheritance in action since the child is nested inside the parent by UI-Router... Commented Feb 2, 2018 at 10:40

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

"UI-Router allows multiple views to be defined on a single state", this is unfortunately not it. My states only contain one view per state.
Take a look at this pluncker: plnkr.co/edit/xHFLyZ1wSk33puZ46vnA. The child inherits to parent scope if the DOM maintein inheritance, if use named views on parent-child states you could break this rule.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.