AngularJS Example Global Function Service

by apspoliveira

HTML

<div ng-app="myApp">
    <div ng-controller="Ctrl1">
        <button ng-click="alertFunc('greet')">Push Me</button>
        <button ng-click="alertFunc('log')">Push Me</button>
    </div>
</div>

CSS

</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script> <style> .ng-invalid {
    border: 1px solid red;
}

JavaScript

function greet(msg) {
    alert(msg);
}

function log(msg) {
    console.log(msg);
}

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

myApp.factory('globalFunctions', function() {
    return {
        greet: greet,
        log: log
    };
});

myApp.controller('Ctrl1', ['$scope', 'globalFunctions', function($scope, globalFunctions) {
        $scope.alertFunc = function(someGlobalFuncReference) {
            var fn = globalFunctions[someGlobalFuncReference];
            if (fn) {
                fn.call(this, 'hie');
            }
        };
}]);