AngularJS - 访问子作用域 [英] AngularJS - Access to child scope

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

问题描述

如果我有以下控制器:

function parent($scope, service) {
    $scope.a = 'foo';

    $scope.save = function() {
        service.save({
            a:  $scope.a,
            b:  $scope.b
        });
    }
}

function child($scope) {
    $scope.b = 'bar';
}

parentchild 中读取 b 的正确方法是什么?如果有必要在 parent 中定义 b,假设 b 是描述与 child 而不是 parent?

What's the proper way to let parent read b out of child? If it's necessary to define b in parent, wouldn't that make it semantically incorrect assuming that b is a property that describes something related to child and not parent?

更新:进一步考虑一下,如果有多个孩子拥有b,那么会在哪个上产生冲突b 检索.我的问题仍然存在,从 parent 访问 b 的正确方法是什么?

Update: Thinking further about it, if more than one child had b it would create a conflict for parent on which b to retrieve. My question remains, what's the proper way to access b from parent?

推荐答案

AngularJS 中的作用域使用原型继承,当在子作用域中查找属性时,解释器将查找从子作用域开始并继续到父作用域的原型链直到它找到财产,而不是相反.

Scopes in AngularJS use prototypal inheritance, when looking up a property in a child scope the interpreter will look up the prototype chain starting from the child and continue to the parents until it finds the property, not the other way around.

查看 Vojta 对该问题的评论 https://groups.google.com/d/msg/angular/LDNz_TQQiNE/ygYrSvdI0A0J

Check Vojta's comments on the issue https://groups.google.com/d/msg/angular/LDNz_TQQiNE/ygYrSvdI0A0J

简而言之:您不能从父作用域访问子作用域.

In a nutshell: You cannot access child scopes from a parent scope.

您的解决方案:

  1. 在父级中定义属性并从子级访问它们(阅读上面的链接)
  2. 使用服务共享状态
  3. 通过事件传递数据.$emit 向上发送事件到父级,直到根作用域,$broadcast 向下发送事件.这可能有助于您在语义上保持正确.
  1. Define properties in parents and access them from children (read the link above)
  2. Use a service to share state
  3. Pass data through events. $emit sends events upwards to parents until the root scope and $broadcast dispatches events downwards. This might help you to keep things semantically correct.

这篇关于AngularJS - 访问子作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆