1

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.

6
  • Could the not-my-controller have been created by a directive? If so, it may be created differently, resulting in your issue. Commented Apr 16, 2014 at 11:06
  • Dunno, but your problem works here: jsfiddle.net/SNLNQ/61 Commented Apr 16, 2014 at 11:12
  • Have you checked out this answer stackoverflow.com/a/14049482/2874153? Commented Apr 16, 2014 at 11:49
  • 1
    Isolated scopes can access parents too. Commented Apr 16, 2014 at 12:49
  • @Erex I have, which is why I thought I understood how it worked which didn't seem to be the case :(. Commented Apr 16, 2014 at 14:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.