Javascript 在 angularjs 服务中编写函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13952046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
writing functions in angularjs services
提问by JSAddict
i want to write a function inside a angularjs service and i want to reuse it in all my
我想在 angularjs 服务中编写一个函数,我想在我所有的
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.
我想在我的任何控制器中使用 daysInMonth 函数。是否可以?如果是这样,有人可以用小提琴中的一些例子简要解释我。
Thanks in advance
提前致谢
采纳答案by Mark Rajcok
If you want a function to be available to allof your controllers, you might consider defining the method on $rootScope, instead of using a service:
如果您希望所有控制器都可以使用一个函数,您可以考虑在 $rootScope 上定义方法,而不是使用服务:
myApp.run(function($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.
JavaScript 不会找到定义在 $scope 上的函数 daysInMonth,因此它会在父作用域(在本例中为根作用域)中查找该函数,并找到它。
回答by Bertrand
Here is fiddle with a basic example of how you can use (inject) services in controllers.
这是一个基本示例,说明如何在控制器中使用(注入)服务。
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.
希望能帮助到你。
回答by Humberto
Expose the function as a service, then let the AngularJS injector do the rest. You can easily set a daysInMonthservice as a static value in your module. See this in action at http://jsfiddle.net/hbulhoes/zdtnw/
将函数作为服务公开,然后让 AngularJS 注入器完成剩下的工作。您可以轻松地将daysInMonth服务设置为模块中的静态值。在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);
}
回答by asgoth
You need to expose it. Wrap it in a return block:
你需要暴露它。将其包装在返回块中:
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() {
return {
daysInMonth: function(month,year) {
return new Date(year, month+1,0).getDate();
}
};
});
回答by SoEzPz
If you want to use the actual Angular Service(not factory, or provider), then all you have to do is the following to create something the Angular way.
如果您想使用实际的 Angular服务(不是工厂或提供者),那么您所要做的就是以 Angular 的方式创建一些东西。
mod.service ('sharedService', function() {
function daysInMonth(month,year) {
return new Date(year, month+1,0).getDate();
}
});
// Would turn into
mod.service("sharedService", function(){
this.daysInMonth(month, year){
return new Date(year, month + 1, 0).getDate();
}
});
You should not RETURNfrom a service unless you NEEDto override the default THISobject that will be created when the service is NEW'ED. In that case, you can return an Object Literal, Function Definition, Array, most Objects excluding any primitives. Just assure you ask the question "why do I need to override the default behavior?"
您不应从服务返回,除非您需要覆盖将在服务NEW'ED时创建的默认THIS对象。在这种情况下,您可以返回对象字面量、函数定义、数组、大多数对象(不包括任何原语)。只要确保你问“为什么我需要覆盖默认行为?”的问题。
That's really the entire point of a service. When you inject the SERVICEAngular will NEWthe function you pass, thus returning it to you as described. In your case, the service will be exactly what you need. Angular will build the Servicejust once, and the new sharedServicefunction result will be available throughout your application, but only when the service is DI'd at least once somewhere in your application. If you don't DI it, then the service will never be created as it is lazily loaded (Factory and Service).
这就是服务的全部意义所在。当您注入SERVICEAngular 时,会将您传递的函数添加到新函数中,从而按照描述将其返回给您。就您而言,该服务正是您所需要的。Angular 将只构建一次服务,并且新的 sharedService函数结果将在整个应用程序中可用,但前提是该服务在应用程序中的某处至少被 DI 一次。如果你不 DI 它,那么服务将永远不会被创建,因为它是延迟加载的(工厂和服务)。
If you find you really want to return something, (although you CAN do it in a service), the appropriate place would be in an Angular Factory. In fact, if you DON'Treturn from a Factoryyou will get a nice little notice
如果你发现你真的想返回一些东西(虽然你可以在服务中做),那么合适的地方应该是在 Angular Factory 中。事实上,如果你不从工厂回来,你会得到一个很好的小通知
ERROR:Provider 'sharedService' must return a value from $get factory method.
错误:提供程序“sharedService”必须从 $get 工厂方法返回一个值。
NOTE:where the $getfunction is the second argument of the service function definition.
注:在$ GET功能是服务功能定义的第二个参数。
mod.factory("sharedService", function(){
function daysInMonth(month, year){
return new Date(year, month + 1, 0).getDate();
}
return {
daysInMonth: daysInMonth
}
// Or you could do this...
return daysInMonth;
});
When using the Angular Factoryyou no longer get a NEW'EDfunction, which is why a return must be created.
使用 Angular Factory 时,您不再获得NEW'ED函数,这就是必须创建 return 的原因。
回答by Jelmer Jellema
I think the OP meant the service isa function, like for example the $timeout function. As the default service factory makes a "service" of whatever you return, you can do this:
我认为 OP 意味着该服务是一个函数,例如 $timeout 函数。由于默认服务工厂为您返回的任何内容制作“服务”,您可以这样做:
angular.module('myApp.myModule',[])
.factory('add',['$injectables',function($injectables) {
return function(arg1,arg2)
{
//this is the function that will be called when you use this service
return arg1 + arg2;
}
}]);
Usage:
用法:
angular.module('myApp.Othermodule',['myApp.myModule'])
.controller('controllername',['add',function(add) {
//controller code and somehwere
$scope.z = add($scope.x,$scope,y);
}]);

