gpt4 book ai didi

javascript - 如何在 Angular 的父 Controller 中访问子 Controller 范围?

转载 作者:可可西里 更新时间:2023-11-01 02:50:28 24 4
gpt4 key购买 nike

我正在学习 Angular JS,我有一个父 Controller 和子 Controller 这样的东西:

<div ng-controller="MainCtrl">
<p>Good {{question}}</p>

<div ng-controller="ChildCtrl">
<p>Good {{answer}}!</p>
</div>

Bind the Child Controller's scope and show here: {{ answer}}
<div>

这里子 Controller 使用这样的范围:

$scope.answer = response.answer;

如何在子 Controller 外部和父 Controller 内部显示 {{ answer }}

最佳答案

您还可以使用作用域原型(prototype)继承。

在 AngularJS 中,子作用域通常原型(prototype)继承自其父作用域。但是 answer 是原始类型(不是对象类型)。所以我们应该把我们的文本数据放到对象中,以确保原型(prototype)继承发挥作用。
(更多信息在这里:https://github.com/angular/angular.js/wiki/Understanding-Scopes)

Controller :

function MainCtrl($scope) {
$scope.question = 'question';
$scope.answer = {};
}
function ChildCtrl($scope) {
$scope.answer.text = 'demo';
}

查看:

<div ng-controller="MainCtrl">
<p>Good {{question}}</p>
<div ng-controller="ChildCtrl">
<p>Good {{answer.text}}!</p>
</div>
Bind the Child Controller's scope and show here: {{ answer.text}}
<div>

关于javascript - 如何在 Angular 的父 Controller 中访问子 Controller 范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22427885/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com