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? 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.