Asked  7 Months ago    Answers:  5   Viewed   87 times

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?

 Answers

78

If your HTML is like below you could do something like this:

<div ng-controller="ParentCtrl">
    <div ng-controller="ChildCtrl">
    </div>
</div>

Then you can access the parent scope as follows

function ParentCtrl($scope) {
    $scope.cities = ["NY", "Amsterdam", "Barcelona"];
}

function ChildCtrl($scope) {
    $scope.parentcities = $scope.$parent.cities;
}

If you want to access a parent controller from your view you have to do something like this:

<div ng-controller="xyzController as vm">
   {{$parent.property}}
</div>

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:

function ParentCtrl($scope) {
    $scope.cities = ["NY","Amsterdam","Barcelona"];
}

function ChildCtrl($scope) {
    $scope.parentCities = $scope.cities;
}

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

<div ng-app ng-controller="ParentCtrl as pc">
    <div ng-controller="ChildCtrl as cc">
        <pre>{{cc.parentCities | json}}</pre>
        <pre>{{pc.cities | json}}</pre>
    </div>
</div>

JS

function ParentCtrl() {
    var vm = this;
    vm.cities = ["NY", "Amsterdam", "Barcelona"];
}

function ChildCtrl() {
    var vm = this;
    ParentCtrl.apply(vm, arguments); // Inherit parent control

    vm.parentCities = vm.cities;
}

If you use the controller as method you can also access the parent scope as follows

function ChildCtrl($scope) {
    var vm = this;
    vm.parentCities = $scope.pc.cities; // note pc is a reference to the "ParentCtrl as pc"
}

As you can see there are many different ways in accessing $scopes.

Updated fiddle

function ParentCtrl() {
    var vm = this;
    vm.cities = ["NY", "Amsterdam", "Barcelona"];
}
    
function ChildCtrl($scope) {
    var vm = this;
    ParentCtrl.apply(vm, arguments);
    
    vm.parentCitiesByScope = $scope.pc.cities;
    vm.parentCities = vm.cities;
}
    
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<div ng-app ng-controller="ParentCtrl as pc">
  <div ng-controller="ChildCtrl as cc">
    <pre>{{cc.parentCities | json}}</pre>
    <pre>{{cc.parentCitiesByScope | json }}</pre>
    <pre>{{pc.cities | json}}</pre>
  </div>
</div>
Tuesday, June 1, 2021
 
jakubos
answered 7 Months ago
10

Don't use this pattern - This will end up causing more errors than it solves. Even though you think it fixed something, it didn't.

You can check if a $digest is already in progress by checking $scope.$$phase.

if(!$scope.$$phase) {
  //$digest or $apply
}

$scope.$$phase will return "$digest" or "$apply" if a $digest or $apply is in progress. I believe the difference between these states is that $digest will process the watches of the current scope and its children, and $apply will process the watchers of all scopes.

To @dnc253's point, if you find yourself calling $digest or $apply frequently, you may be doing it wrong. I generally find I need to digest when I need to update the scope's state as a result of a DOM event firing outside the reach of Angular. For example, when a twitter bootstrap modal becomes hidden. Sometimes the DOM event fires when a $digest is in progress, sometimes not. That's why I use this check.

I would love to know a better way if anyone knows one.


From comments: by @anddoutoi

angular.js Anti Patterns

  1. Don't do if (!$scope.$$phase) $scope.$apply(), it means your $scope.$apply() isn't high enough in the call stack.
Tuesday, June 1, 2021
 
Saurabh
answered 7 Months ago
81

Without seeing the markup, I guess the scope of MenuSideController is a child scope to the scope you are selecting.

While it is possible to traverse down the tree like this (assuming the scope we want is the first child):

var appElement = document.querySelector('[ng-app=theApp]');
var appScope = angular.element(appElement).scope();
var controllerScope = appScope.$$childHead;
console.log(controllerScope.user);

It is simpler to just select the element where the specific controller is attached.

Assuming you are using the ng-controller directive:

<body ng-controller="MenuSideController"></body>

Do instead:

var controllerElement = document.querySelector('body');
var controllerScope = angular.element(controllerElement).scope();
console.log(controllerScope.user);

Demo: http://plnkr.co/edit/WVNDG9sgYgoWaNlrNCVC?p=preview

angular.element(document).ready(function() {

  var appElement = document.querySelector('[ng-app=theApp]');
  var appScope = angular.element(appElement).scope();

  console.log('Traversing from appScope to controllerScope:', appScope.$$childHead.user);


  var controllerElement = document.querySelector('body');
  var controllerScope = angular.element(controllerElement).scope();

  console.log('Directly from controllerScope:', controllerScope.user);


  controllerScope.$apply(function() {
    controllerScope.user.zoomlvl = '10';
  });
});
Monday, June 28, 2021
 
daiscog
answered 6 Months ago
55

Try using ui-router: http://github.com/angular-ui/ui-router.

They have nested views and easier state management than angular default routing :-)

Sunday, September 12, 2021
 
Shinobi_Atobe
answered 3 Months ago
21

Using your code structure, in your child controllers you would need to change:

$scope.$parent.kills++;

to

$scope.$parent.$parent.kills++;

Explanation: MainCtrl's scope is the parent scope of SimpleParentCtrl, but the grandparent of Step1Ctrl and Step2Ctrl. As some others pointed out, ng-switch creates its own scope, and then your Step1Ctrl and Step2Ctrl each created a child scope of the ng-switch.

Note: Each time the 1 or 2 button is clicked, both the ng-switch and it's currently matched child controller get a new scope.

Also: In case you happen to be looking in the Angular source and wondering how the ng-switch directive creates its own scope without a scope property, the answer is that it does so manually in its link method via scope.$new(). The directives ng-include, ng-switch, ng-repeat, and ng-view all create new scope this way, either in the link method or the compile method's returned link function.

Resources:

https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance http://www.youtube.com/watch?v=ZhfUv0spHCY&feature=youtu.be&t=30m

Saturday, October 2, 2021
 
drowneath
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share