<div ng-app="myApp">
<div ng-controller="FirstController">
//In this controller i am having one insert Functionality on ng-click
</div>
<div ng-controller="secondController">
//In this controller i am having one insert Functionality on ng-click
</div>
<div ng-controller="FinalController">
//Here on ng-click i want to trigger all the other controller's click events
</div>
</div>
Actually i am building an angular js app where i have different section's the the user can save his entered data, so for that reason each controller here is behaving as single entity and performing crude operations on button click of each controller. Now as in each controller there is insert functionality implemented on ng-click to send the data to the table. in final controller there is a save button where we need to trigger all the insert click's of different controllers how can i achieve this any quick suggestion's are appreciated.
-
6You can view this question: http://stackoverflow.com/questions/9293423/can-one-controller-call-anotherfaton– faton2016年02月25日 09:28:02 +00:00Commented Feb 25, 2016 at 9:28
4 Answers 4
You can use $rootScope for that. Inject $rootScope into all controllers add then emit an event from finalcontroller to other controllers like this
In final controller
$rootScope.$emit('triggerClick'); // when you want to trigger click in other controllers
In firstController and secondController
$scope.yourFunction = function(){ //This will be executed on ng-click
// InsertFunction code
}
$rootScope.$on('triggerClick', function() { // this will be executed when you trigger from finalController
// InsertFunction code
})
4 Comments
you'll need to broadcast a message from your final controller, and act upon it in the other controllers.
FinalController
function trigger(){
$rootScope.$broadcast('yourEventName');
}
FirstController
$rootScope.$on('yourEventName', function(){
//do your insert functionality
})
Comments
If you want to trigger other controllers actions you must use services.
Implement your trigger actions in a service and then inject it in the other controller.
This is the "best practice" way to do that.
1 Comment
You should use events to communicate between modules / in this case controllers in your angularjs apps. That is the proper approach.
ie using $on, $broadcast and $emit.
Emmiter
function someFunction(){// your buttonclick or whatever you want to sstart communication with
$rootScope.$broadcast('eventName',{data: 100});//this should be remembered
}
Receiver
$rootScope.$on('eventName', function(event,args){// and here is why
// acces with args.data
})
Look at this post , the answers apart from the correct one are also a good dive into the approaches for communication b/w app components.