Angularjs继承父作用域混乱混乱、作用、Angularjs

2023-09-13 04:11:17 作者:斩碎星空

我有一个控制器,这是另一个控制器中。

I have a controller that's inside another controller.

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

我相信UI-如果创建一个新的范围,所以这里有3范围。

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"
})

我可以很容易做到 $范围。$父。$​​ parent.foo ,但我读了范围都应该从父自动继承和家长的事情就是超级笨重。

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.

从Angularjs维基语录:

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?

推荐答案

随着维基说,你不需要做任何事情。只是通过其名称来访问它。

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";
}

有关实例之上将呈现富A和富乙

小提琴这里