I've set up my controllers using data-ng-controller="xyzController as vm"
I have a scenario with parent / child nested controllers. I have no problem accessing parent properties in the nested html by using $parent.vm.property
, but I cannot figure out how to access the parent property from within my child controller.
I've tried injecting $scope and then using $scope.$parent.vm.property
, but this isn't working?
Can anyone offer advice?
From a child component you can access the properties and methods of the parent component with 'require'. Here is an example:
Parent:
Child:
Perhaps this is lame but you can also just point them both at some external object:
The benefit here is that edits in ChildCtrl now propogate back to the data in the parent.
I've just checked
works for me.
and it will be
for the view.
If your HTML is like below you could do something like this:
Then you can access the parent scope as follows
If you want to access a parent controller from your view you have to do something like this:
See jsFiddle: http://jsfiddle.net/2r728/
Update
Actually since you defined
cities
in the parent controller your child controller will inherit all scope variables. So theoritically you don't have to call$parent
. The above example can also be written as follows:The AngularJS docs use this approach, here you can read more about the
$scope
.Another update
I think this is a better answer to the original poster.
HTML
JS
If you use the
controller as
method you can also access the parent scope as followsAs you can see there are many different ways in accessing
$scopes
.Updated fiddle
I believe I had a similar quandary recently
My setup was a little different, but the same thing should probably still work
Super easy and works, but not sure why....