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?

Harry
  • 52,711
  • 71
  • 177
  • 261
  • You just directly access them as if they were in your main scope. [Plunk Here](http://plnkr.co/edit/0a4mFJdSHs275tqCpYvk?p=preview) – rGil May 27 '13 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. – Harry May 27 '13 at 22:57

1 Answers1

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.

emre nevayeshirazi
  • 18,983
  • 12
  • 64
  • 81
  • 7
    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? – Hcabnettek Jun 03 '13 at 17:04
  • 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). – Martin Connell Jan 30 '21 at 00:51