1

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
leandro713
  • 1,268
  • 1
  • 10
  • 17

2 Answers2

3

If you are using it on the controller, seems a candidate for a Service. Once defined, you can use dependency injection to use it in your controller.

This is the simplest snippet on using a service, but there are other ways of defining them. They are very well explained here

var myApp = angular.module('myApp', []);

//define service
myApp.service('helloWorld', function() {
    this.sayHello = function() {
        return "Hello World!"
    };
});

//inject the service
function MyCtrl($scope, helloWorld) {
    alert(helloWorld.sayHello());
}
Community
  • 1
  • 1
Eugenio Cuevas
  • 10,858
  • 3
  • 29
  • 51
  • my question was initially intended for using it on the controller. can you provide an example of globally available function into a Service, like lets say ... `check_email_format()` or `select_menu(item)` ? – leandro713 Sep 19 '13 at 09:24
  • You can apply a method to the `$scope` or `$rootScope` as these are essentially objects, therefore you can assign a method like so: `$scope.foo = function() { console.log('bar'); };`. This will be available in all controllers that are children to the controller's scope you assign this method to. – Ahmed Nuaman Sep 19 '13 at 09:39
1

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

kubuntu
  • 2,525
  • 1
  • 22
  • 24