JK_Jha JK_Jha - 4 days ago 5
AngularJS Question

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.

Answer

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;
             }
        }
    });
}
Comments