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
Perhaps this is lame but you can also just point them both at some external object:
var cities = [];
function ParentCtrl() {
var vm = this;
vm.cities = cities;
vm.cities[0] = 'Oakland';
}
function ChildCtrl($scope) {
var vm = this;
vm.cities = cities;
}
The benefit here is that edits in ChildCtrl now propogate back to the data in the parent.
I believe I had a similar quandary recently
function parentCtrl() {
var pc = this; // pc stands for parent control
pc.foobar = 'SomeVal';
}
function childCtrl($scope) {
// now how do I get the parent control 'foobar' variable?
// I used $scope.$parent
var parentFoobarVariableValue = $scope.$parent.pc.foobar;
// that did it
}
My setup was a little different, but the same thing should probably still work
Super easy and works, but not sure why....
angular.module('testing')
.directive('details', function () {
return {
templateUrl: 'components/details.template.html',
restrict: 'E',
controller: function ($scope) {
$scope.details=$scope.details; <=== can see the parent details doing this
}
};
});
Some times you may need to update parent properties directly within child scope. e.g. need to save a date and time of parent control after changes by a child controller. e.g Code in JSFiddle
HTML
<div ng-app>
<div ng-controller="Parent">
event.date = {{event.date}} <br/>
event.time = {{event.time}} <br/>
<div ng-controller="Child">
event.date = {{event.date}}<br/>
event.time = {{event.time}}<br/>
<br>
event.date: <input ng-model='event.date'><br>
event.time: <input ng-model='event.time'><br>
</div>
</div>
JS
function Parent($scope) {
$scope.event = {
date: '2014/01/1',
time: '10:01 AM'
}
}
function Child($scope) {
}
I've just checked
$scope.$parent.someProperty
works for me.
and it will be
{{$parent.someProperty}}
for the view.
You can also circumvent scope inheritance and store things in the "global" scope.
If you have a main controller in your application which wraps all other controllers, you can install a "hook" to the global scope:
function RootCtrl($scope) {
$scope.root = $scope;
}
Then in any child controller, you can access the "global" scope with $scope.root
. Anything you set here will be globally visible.
Example:
function RootCtrl($scope) {
$scope.root = $scope;
}
function ChildCtrl($scope) {
$scope.setValue = function() {
$scope.root.someGlobalVar = 'someVal';
}
}
function OtherChildCtrl($scope) {
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="RootCtrl">
<p ng-controller="ChildCtrl">
<button ng-click="setValue()">Set someGlobalVar</button>
</p>
<p ng-controller="OtherChildCtrl">
someGlobalVar value: {{someGlobalVar}}
</p>
</div>