In Blogs

When you want to make a function available in every controller you basically have two options. Defining the function as a service or adding it to the $rootScope. But generally, I argue that the $rootScope should be kept as untouched as possible. But if you do need to use the $rootScope then only add static or constants.

The following code shows the use of a service in the controller

<!doctype html>
<html ng-app="myApp">
<head>
 <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
 <script src="http://code.angularjs.org/1.4.8/angular.min.js"></script>
 <script type="text/javascript">
 var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
 return {
 myFunction: function() {
 alert("Message from myService.");
 }
 };
 });
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
 $scope.callMyFunction = function() {
 myService.myFunction();
 }
 }]);
 </script>
</head>
<body ng-controller="MainCtrl">
 <button ng-click="callMyFunction()">Call myFunction</button>
</body>
</html>

The following code shows the use of a global function

<!doctype html>
<html ng-app="myApp">
<head>
 <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
 <script src="http://code.angularjs.org/1.4.8/angular.min.js"></script>
 <script type="text/javascript">
 var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
 $rootScope.myGlobalFunction = function() {
 alert("Message from myGlobalFunction");
 };
 });
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
 </script>
</head>
<body ng-controller="MainCtrl">
 <button ng-click="myGlobalFunction()">Call myGlobalFunction</button>
</body>
</html>?

The code shown here was only for demo purposes. You should really separate the services, controllers and html. How to do this I refer to the great posts on the blog of JohnPapa.?

Vul je zoekopdracht in.