Angularjs inheriting parent scope confusion

冷暖自知 提交于 2019-12-08 05:44:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/16781391/angularjs-inheriting-parent-scope-confusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!