加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 10:14:54 所属栏目:安全 来源:网络整理
导读:https://www.bokeyy.com/post/parent-child-controller-communication.html (译文) https://rclayton.silvrback.com/parent-child-controller-communication(原文) 我最近经在教很多个朋友 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 (子)被另一个 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",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.";
 }]);

"ChildCtrl""I'm the Child.";
);

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读