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

查看:125
本文介绍了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';
}

什么是让 B 儿童?如果有必要来定义 B ,也不会使它语义上不正确假设是介绍与孩子,这也不是一个属性

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 检索。我的问题是,什么是访问的正确方法 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使用原型继承,在子范围查找属性时间preTER将查找原型链从孩子开始,继续给父母,直到它找到的财产​​,而不是其他的方式。

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开发的评论href=\"https://groups.google.com/d/msg/angular/LDNz_TQQiNE/ygYrSvdI0A0J\">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. 通过活动传递数据。 $发出向上将事件发送给家长,直到根范围和 $广播向下调度事件。这可以帮助你使事情语义正确。

  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天全站免登陆