I'm dealing with a simple problem in AngularJS regarding the visibility of functions between controllers and the $scope and $rootScope variables.
To clarify, I have a couple of functions in several of my controllers that I would like to make available in all of them (for the sake of code clarity and avoid duplicating functions).
I already have functions using $rootScope and services for other functionalities, but I can't find the proper way to address this case.
This is one example, one simple function to toggle an accordion list (Source: http://codepen.io/deinerson1/pen/gxnzj)
// Toggle groups
$scope.toggleGroup = function(group) {
if ($scope.isGroupShown(group)) {
$scope.shownGroup = null;
} else {
$scope.shownGroup = group;
}
};
$scope.isGroupShown = function(group) {
return $scope.shownGroup === group;
};
In this case, how can I make this function (that is using $scope) available to all the controllers that may want to use it?
As a summary:
What is the proper way of making functions available globally, including those using $scope variable?
- If I use a function inside $rootScope, how can I access/handle the $scope variable that is being used inside that function?
- Exactly the same question if I use a service.
- And last but not least, what might be the correct/best way of handling this situation if the previous two options are discarded?
Also, to have another example and avoid getting stuck with the simple accordion thing:
$scope.cancelModal = function() {
$ionicHistory.nextViewOptions({
disableBack: true
});
$ionicViewSwitcher.nextDirection('back'); // Go back effect
$state.go('app.main');
}