在angularjs服务编写函数 [英] writing functions in angularjs services

查看:106
本文介绍了在angularjs服务编写函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个angularjs服务中的函数,我想重新使用它在我所有的

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) {
$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任何我的控制器。
可能吗?如果是这样任何人都可以解释我简要地拨弄中的一些例子。

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.

在此先感谢

推荐答案

如果你想成为一个功能可为所有的控制器后,你可能会考虑定义在$ rootScope的方法,而不是使用服务:

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:

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就无法找到$范围定义函数daysInMonth,所以看起来在父范围(在这种情况下,根范围内)的功能,它会找到它。

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.

这篇关于在angularjs服务编写函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆