Basically there are two ways, defining as a service or putting it in its root scope. The ideal is to create a service so as not to pollute its "root" scope.
You can create a service and make it available on your controller like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
$scope.callFoo = function() {
myService.foo();
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="callFoo()">Call foo</button>
</body>
</html>
If it doesn’t roll, you can add us to root scope like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.globalFoo = function() {
alert("I'm global foo!");
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="globalFoo()">Call global foo</button>
</body>
</html>
That way all your templates can call globalFoot()
without having to pass this to the controller template.
Source: https://stackoverflow.com/questions/15025979/can-i-make-a-function-available-in-every-controller-in-angular
I came to create a service to reuse some functions in another module, works, but I can’t reuse another module. for example: in javascript: 1.js>(depends)2.js>(depends)3.js, in agular I thought something like, modulo1>(depends)services>(belonging) modulo2. like where I asked http://answall.com/questions/93558/inje%C3%A7%C3%A3o-de-dependencia-em-service/93562#93562
– Victor Siqueira