Raphael Rafatpanah Raphael Rafatpanah - 3 months ago 18
AngularJS Question

How to share prototype functions in AngularJS?

I have two functions I'd like to share across multiple AngularJS controllers, but I'm not exactly sure how to do this for prototype functions.

Previously, the functions were defined right in the controller:

Array.prototype.contains = function(needle) {

...

}


This allowed any array to be chained using the
contains
method. However, this does not work when placed in a factory since
contains
is undefined for any array outside the service.

(function() {

'use strict';

angular
.module('app')
.factory('FunctionsFactory', FunctionsFactory);

function FunctionsFactory() {

return {
contains: contains,
exactlyContains: exactlyContains
};
...


What is the best way to share these types of functions across multiple AngularJS controllers?

Answer

The best place to have such global common functions is Run Blocks. They are the closest thing in Angular to the Main method.

    angular.module('myApp',  [])
    .run(function(){
        Array.prototype.contains = function(){
             console.log('array contains');
        };    
    });

Run Blocks get executed after the injector is created and are used to kickstart the application.