如何在Angular中访问父控制器中的子控制器范围?

Nee*_*eel 9 javascript scope controller angularjs

我正在学习Angular JS,我有一个类似于父控制器和子控制器的东西:

<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>
Run Code Online (Sandbox Code Playgroud)

子控制器在这里使用这样的范围:

$scope.answer = response.answer;
Run Code Online (Sandbox Code Playgroud)

如何{{ answer }}在子控制器外部和父控制器内部显示?

Iva*_*nZh 18

您还可以使用范围原型继承.

在AngularJS中,子范围通常原型继承自其父范围.但它answer是原始的(不是对象类型).所以我们应该把我们的文本数据放到对象上,以确保原型继承在起作用.
(更多信息请访问:https://github.com/angular/angular.js/wiki/Understanding-Scopes)

控制器:

function MainCtrl($scope) {
  $scope.question = 'question';
  $scope.answer = {};
}
function ChildCtrl($scope) {
  $scope.answer.text = 'demo'; 
}
Run Code Online (Sandbox Code Playgroud)

视图:

<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>
Run Code Online (Sandbox Code Playgroud)


Min*_*hev 13

使用发布/订阅模式:

function MainCtrl($scope) {
  $scope.question = 'question'
  $scope.$on('response', function (evnt, data) {
    $scope.answer = data;
  });
}

function ChildCtrl($scope) {
  $scope.$emit('response', 'demo');
}
Run Code Online (Sandbox Code Playgroud)

在这里演示.