[英]How to get the controller of a form
说我有几种形式,每种形式都有自己的控制器,如下所示
<div ng-controller="MyController1 as ctrl">
<label>Some label </label>
</div>
<div ng-controller="MyController2 as ctrl">
<label>Some label </label>
</div>
我有一个全局控制器,该控制器获取有关表单名称的信息。 现在,我想找到每种形式的控制器。 例如,如果在我的全局控制器函数中获得了第一个表单的名称,那么我如何才能找到其控制器为MyController1? 那有可能吗?
可以从另一个控制器调用一个控制器。 但是,我相信您要解决的问题还有其他地方:您的应用程序架构。
理想情况下,您的应用应“响应”状态的变化。 国家应该放在一个单一的地方(也称为“真理的单一来源”),即。 服务。 然后,您可以根据需要与多个控制器共享该服务状态。
您可以直接从控制器更新服务状态,也可以通过在服务本身上调用方法来更新服务状态。
看下面的例子。 我希望这能阐明一些信息。
干杯!
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.