最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create helper class that can accessed with controller on AngularJS - Stack Overflow

programmeradmin3浏览0评论

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.

I'd like to create a ItemSaveHelper class which I would put the common methods inside and call them from the active controller.

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.

I'd like to create a ItemSaveHelper class which I would put the common methods inside and call them from the active controller.

Share Improve this question asked Jul 6, 2012 at 8:01 Umur KontacıUmur Kontacı 35.5k8 gold badges74 silver badges96 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 20

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/

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: []
    };
});
发布评论

评论列表(0)

  1. 暂无评论