i want to write a function inside a angularjs service and i want to reuse it in all my
controllers.
var mod= angular.module('myapp', ['eventFilters', 'highlight', 'event', 'dayfilter', 'Services']).
config(['$routeProvider', function($routeProvider) {
$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
Service in AngularJS is a function or an object that can be used to share data and the behaviour across the application (controller, directives, filters, other services etc.) or we can say services in AngularJS are objects that are wired together using DI (dependency injection) and it can be used to share and organize ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With