40

How do I create some sort of utils bundle that would be accessible from all my controllers?

I have this route code in my main module:

'use strict';

angular.module('lpConnect', []).
    config(['$routeProvider', function($routeProvider) {
    $routeProvider.
        when('/home', {template: 'views/home.html', controller: HomeCtrl}).
        when('/admin', {template: 'views/admin.html', controller: AdminCtrl}).
        when('/connect', {template: 'views/fb_connect.html', controller: MainAppCtrl}).
        otherwise({redirectTo: '/connect'});
}]);

I want a function that can be common to HomeCtrl, AdminCtrl and MainAppCtrl.

How should I do it in AngularJS?

Mistalis
  • 17,793
  • 13
  • 73
  • 97
Shlomi Schwartz
  • 8,693
  • 29
  • 109
  • 186

2 Answers2

63

The way to define common code in angular is through Services.

You would define a new service like so :

.factory('CommonCode', function ($window) {
        var root = {};
        root.show = function(msg){
            $window.alert(msg);
        };
        return root;
    });

In your controller you would inject this service..like so

function MainAppCtrl($scope,CommonCode)
{
     $scope.alerter = CommonCode;
     $scope.alerter.show("Hello World");
}

Just include CommonCode as an argument to your controller function.. Angular will take care of injecting it for you ( Read on Dependancy Injection ..to understand what is happening here. )

ganaraj
  • 26,841
  • 6
  • 63
  • 59
  • 6
    Anyone else find it.... odd that you define a service by calling the factory method? Seems like some naming improvements would go a long way to increasing approachability of the framework. – bclinkinbeard Aug 13 '12 at 15:58
  • 1
    @bclinkinbeard exactly my thoughts as I'm wrapping my head around AngularJS. `factory()`, `value()`, `constant()`, and `service()` seem to be no more than shortcuts for specific cases of `provide()`, which is intended to be used for defining (providing) services. I guess the docs would benefit from a pull request that puts the above sentence in large letters somewhere. – Anton Strogonoff Oct 20 '12 at 16:31
  • To be frank, when I first started this is what confused me. Factory() generally returns a singleton, as you can see, from the above example. A service() - returns a constructor. A value() and constant() as far as I can tell generally do the same thing. And all these are wrapper ( convenience ) over provide()... – ganaraj Oct 23 '12 at 08:28
  • Is the $window variable essential here? – LazerSharks Oct 28 '13 at 17:52
  • It decouples your code from the global `window` object. So its much easier to test ( mock! ) . – ganaraj Oct 29 '13 at 10:53
  • can you set state of the service in each controller (instead of config at module level) – OMGPOP Jun 25 '15 at 06:15
  • e.g. i need to pass a $scope to the service, so that i dont have to pass in each function – OMGPOP Jun 25 '15 at 06:16
9

Just to update previous answer (which only define what factory is), there are 3 ways to inject dependencies (define common code) in AngularJS:

  • Providers
  • Factories
  • Services

I will not talk much about provider because it is a more laborious method for dependency injection. However, this page explains very well how they work.


Technically, service and factory are used for the same thing. It turns out, a service is a constructor function whereas a factory is not.

From this post:

module.service( 'serviceName', function );

When declaring serviceName as an injectable argument you will be provided with an instance of the function.

module.factory( 'factoryName', function );

When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.


You can use the one you prefer and obtain the same result.

Here is two codes doing exactly the same thing through service first, and then factory:

Service syntax

app.service('MyService', function () {
  this.sayHello = function () {
    console.log('hello');
  };
});

Factory syntax

app.factory('MyService', function () {
  return {
    sayHello: function () {
      console.log('hello');
    }
  }
});
Community
  • 1
  • 1
Mistalis
  • 17,793
  • 13
  • 73
  • 97