I know similar questions has been asked in the past, but I hope to get a better understanding to my specific issue.
I have multiple controllers
managing the view
of a single page. The main reason for this is that the functionality of each controller
is vastly different, and I also combined some functionality that used to be on separate views
. This is also not an issue that will be resolved by creating a service
. I only need to "kick-start" both controllers
.
This is my question: I want to implement a single date filter/method
on the view
, that will call the same method
in both controllers
to do its functionality, and update the view
accordingly.
EDIT: How can I use $scope.on
and $scope.emit
, or $rootScope
to call the function in both controllers
?
As per these previously posted questions:
Here are the two controllers
:
angular.module('portalDashboardApp')
.controller('SocialMentionsAnalysisController', SocialMentionsAnalysisController);
angular.module('portalDashboardApp')
.controller('SocialMentionsListController', SocialMentionsListController);
This is the method
call in my single view
:
ng-change="checkDate()
This is the filter method
that gets called:
NOTE: Each of the controllers
has this method
, and I would like to call both these methods
via my single method call
.
$scope.checkDate = function () {
var dateValues = DatePickerService.checkDate($scope.dateFrom, $scope.dateTo);
$scope.dateFrom = dateValues[0];
$scope.dateTo = dateValues[1];
$sessionStorage.dateFrom = dateValues[0];
$sessionStorage.dateTo = dateValues[1];
pullSocialData();
};
I have done research, and this question is perhaps what I need, but I don't know how to implement it.
The the $on functions with same name will get called with its corresponding single $emit call. I mean, you have multiple $on functions in multiple controllers,
$scope.$on('funtionToTrigger', function(event, args) {
//in first controller
});
$scope.$on('funtionToTrigger', function(event, args) {
//in second controller
});
$scope.$on('funtionToTrigger', function(event, args) {
//in third controller
});
Note: all $on functions' name are same 'funtionToTrigger'.
Once you call $scope.$emit('funtionToTrigger', args);
then all three $on functions will run in all three controllers.
So here, you have write a $on function in each controller.
function SocialMentionsAnalysisController () {
$scope.$on('funtionToTrigger', function(event, dateFrom, dateTo) {
//your code for this controller.
});
}
function SocialMentionsListController() {
$scope.$on('funtionToTrigger', function(event, dateFrom, dateTo) {
//your code for this controller.
});
}
Then call $emit on onChange
.
ng-change="$emit('funtionToTrigger', dateFrom, dateTo)"