javascript 如何创建可以使用 AngularJS 上的控制器访问的辅助类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11358199/
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
How to create helper class that can accessed with controller on AngularJS
提问by Umur Kontac?
how can I create a helper/utility class that can be accessible from the multiple controllers?
如何创建可从多个控制器访问的帮助程序/实用程序类?
For example, I have two controllers: UpdateItemCtrl
and CreateItemCtrl
. These have common functions inside which increases redundancy and lowers managability.
例如,我有两个控制器:UpdateItemCtrl
和CreateItemCtrl
. 这些内部具有通用功能,可增加冗余并降低可管理性。
I'd like to create a ItemSaveHelper
class which I would put the common methods inside and call them from the active controller.
我想创建一个ItemSaveHelper
类,我会将常用方法放入其中并从活动控制器调用它们。
回答by Andrew Joslin
You want to create a service.
你想创建一个服务。
A service is just a singleton that can be injected into different things to provide modular/shared functionality. Here's a simple example: http://jsfiddle.net/andytjoslin/pHV4k/
服务只是一个可以注入不同事物以提供模块化/共享功能的单例。这是一个简单的例子:http: //jsfiddle.net/andytjoslin/pHV4k/
function Ctrl1($scope, itemManager) {
$scope.addItem = function(text) {
itemManager.items.push(text);
};
}
function Ctrl2($scope, itemManager) {
$scope.items = itemManager.items;
}
app.factory('itemManager', function() {
return {
items: []
};
});