writing functions in angularjs services
Expose the function as a service, then let the AngularJS injector do the rest. You can easily set a daysInMonth
service as a static value in your module. See this in action at http://jsfiddle.net/hbulhoes/zdtnw/
var mod = angular.module('myapp', []);
// This is the declaration of the daysInMonth service. It's set as
// a value in the module, with the value being the very function
// you want to share among other services and controllers:
mod.value('daysInMonth', function(month, year) {
return new Date(year, month+1,0).getDate();
});
// And this is an example controller that depends on the daysInMonth function.
function MyController($scope, daysInMonth){
$scope.DaysInCurrentMonth = daysInMonth(12, 2012);
}
Here is fiddle with a basic example of how you can use (inject) services in controllers.
http://jsfiddle.net/uhmNR/1/
var myApp = angular.module('myApp',[]);
//Here is the service Users with its functions and attributes
//You can inject it in any controller, service is a singleton and its data persist between controllers
myApp.factory('Users', function () {
var userName = "John Doe";
return {
getUserName: function () {
return userName;
},
setUserName: function (newName) {
userName = newName;
}
}
});
//An Util service with DaysInMonth method
myApp.factory('Util', function () {
return {
daysInMonth: function (month,year) {
return new Date(year, month+1,0).getDate();
}
};
});
//Here I am injecting the User service andusing its methods
myApp.controller('MyCtrl', ['$scope', 'Users', 'Util', function ($scope, Users, Util) {
Users.setUserName('Robin Hood');
$scope.name = Users.getUserName();
//Using Util.daysInMonth()
$scope.date = Util.daysInMonth(12,2012);
}]);
Hope It helps.