0

I have an issue with scope inheritance in AngularJS. The issue is simlar to Angularjs inheriting parent scope confusion but somehow the answer doesn't seem to apply to me.

I have a bunch of controllers (using some external components so I don't have full control over all controllers used) that are nested. The outermost controller and the innermost controller are defined by myself like so:

<div ng-controller="my-outer-controller">
  <div ng-controller="not-mycontroller">
    <div ng-controller="more-controllers">
      <div ng-controller="my-inner-controller">
      </div>
    </div>
  </div>
</div>

function myOuterController(@scope) {
    @scope.someFunction = function() {
    }
}


function myInnerController(@scope) {
    // This function does not exist here!
    @scope.someFunction();
}

The function someFunction() is not available in the inner controller. First I thought there must be some directive that makes an isolated scope in between but when I when I do something like the following it does work:

@scope.$parent.$parent.someFunction()

Just when I thought I had a pretty good understanding as to how Angular scopes work they knock me back down to earth.

I'm sure there's a good explanation as to why this is happening, but I can't see it. I thought that any property you can access via $parent is automatically inherited by the child scope.

Community
  • 1
  • 1
Robba
  • 7,684
  • 12
  • 48
  • 76

1 Answers1

0

I know this is an old question, but I thought this may help other users facing your issue.

I suggest trying using the alias syntax on your controller.

It will simplify your code and probably clarify what you're trying to do.

The alias syntax avoids injecting $scope directly and makes clearer which controller one is using.

Check this awesome explanation out.

I hope it helps.

U r s u s
  • 6,680
  • 12
  • 50
  • 88