undefined
undefined

Reputation: 3622

Calling a controller inside a factory method

Currently I have a factory method like this:

            open_model: function(som_id){
                var modelSettings = $aside({
                    controller: // a very big controller code
                    size: 'sm',
                    placement: 'right',
                    templateUrl: 'views/id/modal.html',
                    resolve: {
                        modal_data: function(){
                            return area_id;
                        }
                    }
                });
            },

I want to separate out the controller from this method and call it by name. Currently this is >100 lines of code in controller section and hence it makes factory dirty. So is there a way to define the controller somewhere else, and call the controller by name instead of writing the code.

Upvotes: 3

Views: 747

Answers (3)

Lizzy
Lizzy

Reputation: 2153

In addition to @nikjohn's answer, you can also create a separate angular controller and refer it within you modelSettings. Since you already said your controller code for the modal exceeds 100 lines, this even might be a better solution.

angular.module('myApp').controller('ModalInstanceCtrl', ['$scope', 'modal_data', function($scope, modal_data) {
    // modal controller code goes here
}]);

// and refer it in your factory method
open_model: function(som_id){
    var modelSettings = $aside({
        controller: 'ModalInstanceCtrl'
        size: 'sm',
        placement: 'right',
        templateUrl: 'views/id/modal.html',
        resolve: {
             modal_data: function(){
                  return area_id;
             }
        }
    });
}

Upvotes: 3

Yatrix
Yatrix

Reputation: 13775

You should never access a controller within a factory. You're mixing concerns by doing that. If there's functionality you want to separate out, create another service and inject that service into your factory. Your controller should be leveraging services and factories, not the other way around.

Upvotes: 0

nikjohn
nikjohn

Reputation: 21802

You can define your controller wherever you want, and inject it as a dependency into your factory (although I don't know what a controller would be doing within a factory).

controllerFn: function(a, b) {
   // ......
}

open_model: function(som_id, controllerFn){
            var modelSettings = $aside({
                controller: controllerFn,
                size: 'sm',
                placement: 'right',
                templateUrl: 'views/id/modal.html',
                resolve: {
                    modal_data: function(){
                        return area_id;
                    }
                }
            });
        },

Upvotes: 1

Related Questions