0

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?

  1. If I use a function inside $rootScope, how can I access/handle the $scope variable that is being used inside that function?
  2. Exactly the same question if I use a service.
  3. 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');
}
3
  • create a factory,define functions inside this factory and then inject that factory name to every controller. Commented Feb 17, 2016 at 10:05
  • I would definitely use a factory for that no doubt Commented Feb 17, 2016 at 10:21
  • But how to define a factory with multiple functions? And also, how to handle $scope inside that factory? Commented Feb 17, 2016 at 13:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.