简体   繁体   English

如何获取表格的控制器

[英]How to get the controller of a form

Say I have several forms each with their own controller that look like this 说我有几种形式,每种形式都有自己的控制器,如下所示

 <div ng-controller="MyController1 as ctrl">
    <label>Some label </label>
</div>

<div ng-controller="MyController2 as ctrl">
    <label>Some label </label>
</div>

And I have a global controller, that gets the information about the form names. 我有一个全局控制器,该控制器获取有关表单名称的信息。 Now I want to find the controllers for each form. 现在,我想找到每种形式的控制器。 For instance, if in my global controller function, I get the name of the first form, how can I find out that its controller is MyController1? 例如,如果在我的全局控制器函数中获得了第一个表单的名称,那么我如何才能找到其控制器为MyController1? Is that even possible? 那有可能吗?

Calling a controller from another controller is possible. 可以从另一个控制器调用一个控制器。 But, I believe the problem you're trying to solve is somewhere else: the architecture of your app. 但是,我相信您要解决的问题还有其他地方:您的应用程序架构。

Ideally, your app should 'react' to changes on the state. 理想情况下,您的应用应“响应”状态的变化。 The state should be kept in a single place (also called 'single source of truth'), ie. 国家应该放在一个单一的地方(也称为“真理的单一来源”),即。 a service. 服务。 Then you share that service state with as many controllers as you need. 然后,您可以根据需要与多个控制器共享该服务状态。

You can either update the service state directly from the controller, or by calling a method on the service itself. 您可以直接从控制器更新服务状态,也可以通过在服务本身上调用方法来更新服务状态。

Look at the example below. 看下面的例子。 I hope that sheds some light. 我希望这能阐明一些信息。

Cheers! 干杯!

 angular.module('app', []) .service('MyService', function(){ var self = this; self.state = { name: 'John' }; self.changeNameFromService = function() { self.state.name = 'Peter'; } }) .controller('Ctrl1', function($scope, MyService){ $scope.state = MyService.state; $scope.changeName = function(){ // update the state of the scope, which is shared with other controllers by storing the state in a service $scope.state.name = 'Mary'; } }) .controller('Ctrl2', function($scope, MyService){ $scope.state = MyService.state; // call a method defined in service $scope.changeName = MyService.changeNameFromService; }) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app"> <div ng-controller="Ctrl1"> Ctrl1: {{state.name}} <button ng-click="changeName()">Change name!</button> </div> <div ng-controller="Ctrl2"> Ctrl2: {{state.name}} <button ng-click="changeName()">Change name from service!</button> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM