Set parent controller property from child controller in "Controller As" syntax

54 views
Skip to first unread message

nideesh manian

unread,
Oct 13, 2015, 11:48:47 AM10/13/15
to AngularJS
I am using "controlleras" syntax. I have main controller with ng-view, with each child page having its own child controller. I wish to set the property of main controller through JS from my child controller pages. I am using this as reference http://codetunnel.io/angularjs-controller-as-or-scope/
In my below code i have two textboxes one in main controller and other in child. If i type in either of the textboxes, both textboxes are updating simultaneously and working as expected. But i want to set the value of "main.data.message" from a JS function. There are two ways which i found $scope.$parent.main.data.message or simply $scope.main.data.message. But i do not want to inject $scope, i wanted to use controller syntax. How it is working inside my child view html pages as expression {{pobj.property}} and not inside controller as "var a = pobj.propoerty" as according to the below url they are saying the childscope should have parentscope properties

Main.html

<html  ng-controller="IndexController as main">
<body>
<input type="text" ng-model="main.data.message"/>
    {{main.data.message}}
 <section ng-view ></section>
</body>
</html>

Main controller
var POSapp = angular.module('POS', ['ngRoute', 'blockUI', 'ngSanitize', 'ngGrid', 'ngAnimate', 'Directives', 'Translation', 'Authentication']);
POSapp.controller("IndexController", [ '$location', function ( $location ) {
        var vm = this;        
        vm.initializeController = function () {
            vm.data = {"message":"testing"};
        }
    }]);


child pages

<div>
        <input type="text" ng-model="main.data.message" />
        {{main.data.message}}         
</div>
POSapp.controller("SalesController", SalesController);
function SalesController()
{
var vm = this;
 console.log($scope.main);
 console.log($scope.$parent.main);

// below are erroring out
 console.log($scope.$parent.main);
 console.log($scope.$parent.main);
 console.log($scope.$parent.main);
}

Sander Elias

unread,
Oct 13, 2015, 11:42:03 PM10/13/15
to AngularJS
Hi NiDeesh,

You have to inject $scope in your child controller for this to work. After that, you can use $scope.controllerIWantToTargetName (in your case $scope.main) 
Do not put in $parent references anywhere! Those will wreck havoc in the future....

Regards
Sander

nideesh manian

unread,
Oct 15, 2015, 10:41:07 AM10/15/15
to AngularJS
Thanks.
Reply all
Reply to author
Forward
0 new messages