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",function($scope){ // Nothing defined on $scope }]); 你会得到像这样的输出结果:
如果子 scope 中定义了父 scope 中的同名变量,父 scope 中那个变量在子 scope 中会被隐藏起来。 在上一个例子中,子 scope 继承了父 scope 中的 app.controller("ParentCtrl", [ '$scope'function($scope){
$scope.title = "I'm the Parent.";
}]);
"ChildCtrl""I'm the Child.";
);
父 scope 中的 $scope.title 的值会被隐藏,当然,仅限在这个子 scope 中发生(父 scope 中的变量是独立的): 子 scope 可以直接访问(甚至修改)父 scope 中的值,但是反过来却不行。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |