now I have some experience dealing with angularjs I wonder often how to having global functions (commonly used in many controllers) accessibles in the whole app. my problem is $scope is only accesible in its controller, I can imagine a solution adding these functions to $rootScope, but for now I only have added variables to $rootScope, I don't know how to add functions and, specially, where do that.
You can use a service which is injected into any controller that requires the function as already mentioned. However, if you prefer to define the function on the $rootScope
, you can do something like this:
app.run(function ($rootScope) {
$rootScope.add = function (a, b) {
return a + b;
}
});
Then you can simple use this function in a controller as
app.controller('Ctrl', function($scope) {
$scope.mySum = $scope.add(5, 7);
});
Here is a working fiddle Function in $rootScope