0
\$\begingroup\$

In my app I have a BaseCtrl, which is attached to the body element and is available everywhere. In the mentioned controller I have the following code for opening modal:

    $scope.addFolder = function($event) {
        $event.preventDefault();

        // Opens an add folder modal
        var modal = ModalService.custom({
            templateUrl: '/partials/modals/create-folder.html',
            controller: ['$scope',
                function($innerScope) {
                    $innerScope.modal = modal;

                    $innerScope.create = function() {
                        var result = NodesService.createFolder($innerScope.new_folder, $scope.location);
                        result.then(function(resp) {
                            modal.close();
                            ModalService.flash('CREATED_SUCCESSFULLY');
                            $rootScope.$emit('update_nodes');
                        }, function(err) {
                            $innerScope.create_folder_error = Locales.get(err.data.message);
                        });
                    };

                }
            ]
        });
    };

I thought it's the most appropriate place to put this snippet, since I need to be able to access it app-wide. My question is should I separate this method in different controller or should I place it in a factory/service? What is the right place to put such code in angular?

\$\endgroup\$
1
\$\begingroup\$

This depends on how the rest of your app feels about the function you're publishing and how modular you want your app to be. If you want absolute modularity, you'll put the functionality in a service and inject & publish it anywhere you want to use it. The same goes for functionality that is reused just in some very specific areas, not really by the whole application.

Sharing functionality using scope hierarchy (especially by putting it on the outer-most scope) is just a way to simplify your code by sacrificing transparency (of dependencies), so in the end, it's up to you to evaluate whether the gain is worth the price in your particular situation.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.