搜索
您的当前位置:首页正文

angularJS controller 控制器获取控制父子级标签

来源:好走旅游网

https://www.bokeyy.com/post/parent-child-controller-communication.html (译文)

https://rclayton.silvrback.com/parent-child-controller-communication(原文)

 

我最近经在教很多个朋友 AngularJS,而他们几乎都问了同样一个问题:

这是个好问题。通常对初学者来说,它不直观。答案比我们想的要复杂(但实现起来很简单)。

有好多方法可以在 controller 之间通信 。在接下来一系列的博文中(译者注:链接见文末),我会展示这些方法,并讨论它们原理上的缺点。

本文中,我会讨论最简单、也最容易滥用的方法:

父子 Controller 通信

和名称一样,这种方法只在一个 controller (子)被另一个 controller (父)所包含的情况下可用。

<div ng-controller="ParentCtrl">
    <div ng-controller="ChildCtrl"></div>
</div>  

在 AngularJS 中,Scope 是 controller 的上下文(view 层可用的数据)。它是可以继承的。也就是说,父 controller 中定义的变量和函数对子 controller 来说也是可用的。这里有一些例子:

父 controller 中定义的变量会应用到子 controller 中。

看看如下结构:

<div ng-controller="ParentCtrl">
    <h1>{{ title }}</h1>
    <div ng-controller="ChildCtrl">
        <h1>{{ title }}</h1>
    </div>
</div>

假设这些 controller 定义如下:

app.controller("ParentCtrl", [ '$scope', function($scope){
    $scope.title = "I'm the Parent.";
 }]);

app.controller("ChildCtrl", [ '$scope', function($scope){
    // Nothing defined on $scope
}]);

你会得到像这样的输出结果:

如果子 scope 中定义了父 scope 中的同名变量,父 scope 中那个变量在子 scope 中会被隐藏起来。

在上一个例子中,子 scope 继承了父 scope 中的 $scope.title 变量。如果子 scope 定义了自己的 $scope.title :

app.controller("ParentCtrl", [ '$scope', function($scope){
    $scope.title = "I'm the Parent.";
 }]);

app.controller("ChildCtrl", [ '$scope', function($scope){
    $scope.title = "I'm the Child.";
}]);

父 scope 中的 $scope.title 的值会被隐藏,当然,仅限在这个子 scope 中发生(父 scope 中的变量是独立的):

子 scope 可以直接访问(甚至修改)父 scope 中的值,但是反过来却不行。

因篇幅问题不能全部显示,请点此查看更多更全内容

Top