Angularjs 继承父作用域混淆 [英] Angularjs inheriting parent scope confusion

查看:27
本文介绍了Angularjs 继承父作用域混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,它在另一个控制器内.

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

我相信 ui-if 创建了一个新的作用域,所以这里有 3 个作用域.

我希望页脚控制器能够访问帖子的范围.

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

我可以很容易地做 $scope.$parent.$parent.foo 但我读到范围应该自动从父级继承,而父级的东西非常笨拙.

引自 Angularjs 维基:

<块引用>

(如果你真的想通过控制器作用域继承来共享数据,您无需执行任何操作.子作用域将有权访问所有父作用域属性.另请参阅控制器加载顺序加载或导航时不同)

如何从页脚范围访问 foo?

解决方案

正如维基所说,你不需要做任何事情.只需通过其名称访问它.

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

功能后($范围){$scope.fooA = 'Foo A';}功能页脚($scope){$scope.fooB = $scope.fooA + " 和 Foo B";}

例如上面将呈现 Foo A 和 Foo B

在这里小提琴.

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?

解决方案

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.

这篇关于Angularjs 继承父作用域混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆