Prashanth Suriyanarayanan Prashanth Suriyanarayanan - 1 year ago 74
AngularJS Question

writing functions in angularjs services

i want to write a function inside a angularjs service and i want to reuse it in all my


var mod= angular.module('myapp', ['eventFilters', 'highlight', 'event', 'dayfilter', 'Services']).
config(['$routeProvider', function($routeProvider) {
when('/', {templateUrl: 'template.html', controller: Ctrl}).
when('/temp', {templateUrl: 'temp.html', controller: tempCtrl}).
otherwise({redirectTo: '/invalid'});
mod.service ('sharedService', function() {
function daysInMonth(month,year) {
return new Date(year, month+1,0).getDate();

i want to use the daysInMonth function in any of my controller.
is it possible? if so could anyone explain me briefly with some examples in fiddle.

Thanks in advance

Answer Source

If you want a function to be available to all of your controllers, you might consider defining the method on $rootScope, instead of using a service:$rootScope) {
    $rootScope.daysInMonth = function(year, month) {
        return new Date(year, month+1,0).getDate();

Then, due to prototypal scope inheritance, all of your controllers' scopes will have access to the method (without the need for dependency injection). You can call it in any controller like so:

function MyCtrl($scope) {
   console.log($scope.daysInMonth(12, 2012));

JavaScript won't find function daysInMonth defined on $scope, so it will look in the parent scope (in this case the root scope) for the function, and it will find it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download