【问题标题】:How to access Child Controller Scope in Parent Controller in Angular?如何在 Angular 的父控制器中访问子控制器范围?
【发布时间】:2014-04-21 02:17:01
【问题描述】:

我正在学习 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>

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

$scope.answer = response.answer;

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

【问题讨论】:

    标签: javascript angularjs controller scope


    【解决方案1】:

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

    在 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'; 
    }
    

    查看:

    <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>
    

    【讨论】:

    • 就是这么简单轻松!我发现这种方法比$emit$on 更好。谢谢@IvanZh
    【解决方案2】:

    使用发布/订阅模式:

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

    Demo here.

    【讨论】:

    • 谢谢敏科。我看了演示。如果父控制器中的{{ answer}} 与子控制器中的{{ answer }} 绑定,是否应该显示demo
    • 其实有一个错误。现在应该修好了。
    • 只是一个小问题。 $scope.$on('response', function (evnt, data) 中的 evnt 是否必须是 event 或者没关系,它可以容纳任何字符串。 (对不起,如果这听起来很傻)
    • @Neel,没关系,你可以使用任何字符串,有时我们使用'e'
    猜你喜欢
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多