I'm using "controller as" syntax and I have each controller in a separate file wrapped in an IIFE, as recommended in John Papa's AngularJS Style Guide.
Is there a way to access properties declared in the scope of the parent controller from the child controller?
I can access them in the view by doing {{parent.variableOfParent}}
, but don't know how to do that from the JS of the child controller.
Plnkr
P.S. It may be good to create a tag for the style guide as there are quite a few questions about it.
You're in essence talking about sharing data between controllers. Well according to me [and by others too ;)], the best way to do so is using services..
Create a service.
Inject the service in both your controllers and save the service reference in the scope of the controllers.
You can now access the data in both view and controllers.
yourApp.service("sharedService", function() {
this.data = "123";
})
yourApp.controller("parentController", function(sharedService) {
$scope.sharedService = sharedService;
});
yourApp.controller("childController", function(sharedService) {
$scope.sharedService = sharedService;
});
Now anything that you want to "share" between the two controllers, can be placed inside the service.
Also, in the html, you can use the same service reference to access the data :
e.g.
<div ng-app='app' ng-controller='ParentCtrl as parent'>
<div ng-controller='ChildCtrl as child'>
{{parent.sharedService.data}}<br> <!-- both will print the same value -->
{{child.sharedService.data}}<br> <!-- both will print the same value -->
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With