0

I have created a test located on plunker at this address: Full example on plunker

Here is the child controller which works:

  child.directive('child', function(){
    return{
      restrict:'E',
      templateUrl: 'child.html',
      link: function(){},
      controller:['$scope', function($scope){
        this.inherited = $scope.test;
        this.local = "child";
      }],
      controllerAs:'child'
    };
  });

I am expecting the controller located in child.js to be a child controller of the controller in script.js. This would mean that if I want to access a variable added to the scope of parent controller from the child controller, I would need to access it using $scope.$parent. Can someone explain why these are the same scope?

n01d3a
  • 17
  • 5

3 Answers3

0

The child scope inherits from the parent scope, so anything you define in the parent will appear in the child scope. Keep in mind that this is a new scope, so modifications won't affect the parent directly without using the $scope.$parent scope. Take a look at this question and the accepted answer: AngularJS access parent scope from child controller

Community
  • 1
  • 1
austin
  • 5,816
  • 2
  • 32
  • 40
  • Except that in directives the parent scope is inherited by default, so you don't have to use $parent to access these values. – Rob R Feb 22 '15 at 03:08
0

In directives the parent scope is inherited by default:

https://github.com/angular/angular.js/wiki/Understanding-Scopes

Rob R
  • 1,011
  • 8
  • 10
0

By default, directives do not create a new scope. So in your example $scope in the directive will be the same value as the scope that the controller is contained in. The scope is not inherited - they are the same scope.

So for this markup:

<div ng-controller="SomeController">
    <child></child>
</div>

scope in SomeController will be the exact same object as scope in your directive. If you did $scope.$parent in the directive, you would actually be accessing the parent scope of SomeController. This is equivalent to

scope: false //default for directives

If you add:

scope: true

to your directive definition, then the directive will create a new scope that prototypically inherits from the parent scope. In this situation,

<div ng-controller="SomeController">
    <child></child>
</div>

Now $scope.$parent in the directive will be the $scope of SomeController. Also, since it prototypically inherits, the directive will have access to methods and properties defined on $scope.$parent, with the caveats and complications that come with prototypically inheritance in javascript.

If you use:

scope: {}

Now $scope.$parent in the directive will still be the $scope of SomeController, but the new scope will not prototypically inherit from the parent, so you will not have access to methods and properties defined on $scope.$parent.

Joe Enzminger
  • 11,110
  • 3
  • 50
  • 75