我想在 angularjs 服务中编写一个函数,并且我想在我的所有服务中重用它
控制器。
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();
}
});
我想在我的任何控制器中使用 daysInMonth 函数。
是否可以?如果是的话,有人可以用小提琴中的一些例子简要解释我。
提前致谢
这是一个关于如何在控制器中使用(注入)服务的基本示例。
http://jsfiddle.net/uhmNR/1/ 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);
}]);
希望能帮助到你。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)