Raphael Rafatpanah Raphael Rafatpanah - 10 months ago 52
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
method. However, this does not work when placed in a factory since
is undefined for any array outside the service.

(function() {

'use strict';

.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?


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',  [])
        Array.prototype.contains = function(){
             console.log('array contains');

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