I have an abstract parent view that is meant to share a controller with its nested views.
.state('edit', {
abstract: true,
url: '/home/edit/:id',
templateUrl: 'app/templates/editView.html',
controller: 'editController'
})
.state('edit.details', {
url: '/details',
templateUrl: 'app/templates/editDetailsView.html'
})
.state('edit.info', {
url: '/info',
templateUrl: 'app/templates/editInfoView.html'
})
The routing works as expected.
The problem is that when I update a $scope
variable from one of the nested views, the change is not reflected in the view. When I do the same from the parent view, it works fine. This is not situation that requires an $apply
.
My guess is that a new instance of editController
is being created for each view, but I'm not sure why or how to fix it.
Based on a comment by PilotBob
I decided to append another solution, using
controllerAs
while keeping the above/original conceptThere is a working plunker
The states would be now having different controllers and parent state will name it "parentCtrl" (to be NOT overwritten in a child scope with child controller)
And these are controllers:
Check it in action here
The issue here would be related to this Q & A: How do I share $scope data between states in angularjs ui-router?.
The way how to solve it is hidden in the:
Understanding Scopes
And also this
Scope Inheritance by View Hierarchy Only
Having that we should do this in edit Controller
And we can even reuse that
controller: 'editController'
(we can do not have to, because the $scope.Model will be there - thanks to inheritance)Now, the same controller will be instantiated many times (parent all the children) but the
$scope.Model
will be initiated only once (inside of parent) and available everywhereCheck this similar working example here
Another alternative using
resolve
In the child controller you can do:
In case the controller is used with alias e.g. 'vm' you can do: