Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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 中的变量是独立的):

@L_489_14@)父 scope 中的值,但是反过来却不行。

大佬总结

以上是大佬教程为你收集整理的angularJS controller 控制器获取控制父级标签全部内容,希望文章能够帮你解决angularJS controller 控制器获取控制父级标签所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。