1

I have a controller that's inside another controller.

<div ng-controller="post">
  <div ui-if="isAllowed">
    <footer ng-controller="footer"></footer>
  </div>
</div>

I believe the ui-if creates a new scope so there's 3 scopes here.

I want the footer controller to be able to access the scope of post.

.controller('post', function($scope) {
  $scope.foo = "bar"
})

I can easily do $scope.$parent.$parent.foo but I read that scopes are supposed to automatically inherit from the parent, and the parent thing is just super unwieldy.

Quote from Angularjs wiki:

(If you really want to share data via controllers scope inheritance, there is nothing you need to do. The child scope will have access to all of the parent scope properties. See also Controller load order differs when loading or navigating)

How do I access foo from the footer scope?

2
  • You just directly access them as if they were in your main scope. Plunk Here Commented May 27, 2013 at 22:51
  • @rGil oh you're right. I was looking at Batarang which showed the scopes separately, but now I realize that's not what that means haha. Thank you. Commented May 27, 2013 at 22:57

1 Answer 1

3

As wiki said, you do not need to do anything. Just access it via its name.

<div ng-controller="post">
  <div ui-if="isAllowed">
    <footer ng-controller="footer">
        {{ fooB }} 
    </footer>
  </div>
</div>

function post($scope) {
    $scope.fooA = 'Foo A';
}

function footer($scope) {
    $scope.fooB = $scope.fooA + " and Foo B";
}

For instance above will render Foo A and Foo B

Fiddle here.

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

2 Comments

What could the problem be if this in not working? I'm using Angular-loader and when I try to call methods on a parentscope, I get an 'undefined' error that method doesn't exist on object? Any ideas how to remedy that?
An 'isolated' scope in a directive is a reason why this will not work. NB: setting scope:true in the directive definition ensures you don't get an isolated scope but get a normal one which will inherit properties from the ancestor scope(s).

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.