I'm using the Controller as in my view as follows:
<body ng-controller="MainCtrl as main"> <div ng-controller="ChildCtrl as child"> {{ main.parentValue }} + {{ child.childValue }} </div> </body>
Defining my controller like this:
app.controller('MainCtrl', function($scope) { this.parentValue = 'Main'; }); app.controller('ChildCtrl', function($scope) { this.childValue = 'Child'; // I want to access the property of the parent controller here });
How can the ChildCtrl set the name property of the MainCtrl? Here the Plunkr.
Using the $scope notation, I could have accessed $scope.parentValue from the child controller. How can the same functionality be achieved using the Controller As notation?
39) Do you think that parent controller can access the methods of child controller or vice versa? No, the parent controller cannot access the methods of child controller, but the child controller can access the methods of the parent controller.
Parent and Child Scopes You can create a new child scope by calling a script or function. The calling scope is the parent scope. The called script or function is the child scope. The functions or scripts you call may call other functions, creating a hierarchy of child scopes whose root scope is the global scope.
AngularJS Scope The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.
Since your using the "controller as" notation, witin your ChildCtrl
you can access the MainCtrl
using $scope.main
, for example $scope.main.name
.
See my snippet below.
var app = angular.module('app', []); app.controller('MainCtrl', function($scope) { this.name = 'Main'; this.test = {}; }); app.controller('ChildCtrl', function($scope) { this.name = 'Child'; alert($scope.main.name); });
<html ng-app="app"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-controller="MainCtrl as main"> <div ng-controller="ChildCtrl as child"> {{ main.name }} + {{ child.name }} </div> </body> </html>
You should not mix up "controller as" and $scope usage. To update data in a parent-scope you could/should use services.
Example: Changing the page-title from within any Child-Controller:
app.service("SiteService", function () { return { title: "Page title"; } } app.controller ("ParentCtrl", function (SiteService) { this.site = SiteService; } app.controller ("ChildCtrl", function (SiteService) { SiteService.title = "New Title"; }
And your template
<html ng-app="someApp" ng-controller="ParentCtrl as site"> <head> <title>{{site.title}}</title> </head> </html>
The main advantage of this approach: You separate public mutable from private properties.
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