snaggs
snaggs

Reputation: 5713

How to solve controller multi arument form in Angular?

I have about 10 controllers and 20 services.

Each controller uses at least 5 the same services and modules. For example:

app.controller('GroupsCtrl', function(
        $rootScope,
        $scope,
        service1,
        service2,
        service3,
        service4,
        service5,
        service6,
         ...
         service20

                )
        { /**/}

It seems pretty ugly and messy.

Is Angular provide any solution that will solve multi argument problem? For example new form:

app.controller('GroupsCtrl', function(
            $rootScope,
            $scope,
            SomeObject, // goes here that contains other absent services

            service6,
             ...
             service20

                    )
            { /**/}

And SomeObject will install absent services:

   SomeObject:[
         service1,
        service2,
        service3,
        service4,
        service5,
        ]

So after that all my 10 controllers can inherit SomeObject instead to write full list each time.

Hope it was clear,

Thanks,

Upvotes: 2

Views: 55

Answers (2)

guru
guru

Reputation: 4022

One simple solution can be using the $inject property annotation to inject the array of service names and referr the services using the arguments array as below.

//Common services array
var commonServices = ['$scope','$http'];
function initiateCtl(services){
    this.scope = services[0]; this.http = services[1]; 
}

//Controller 1
var sampleCtrl = function(){
    initiateCtl(arguments);
    var $window = arguments[2];
    console.log(scope);    
};
sampleCtrl['$inject'] = commonServices.concat(['$window']);
app.controller('sampleCtrl', sampleCtrl);

//Controller 2
var sampleCtrl2 = function(){
    initiateCtl(arguments);
    var $location= arguments[2];
    console.log(scope);    
};
sampleCtrl2['$inject'] = commonServices.concat(['$location']);
app.controller('sampleCtrl2', sampleCtrl2 );

Upvotes: 0

Mathews
Mathews

Reputation: 909

Yes you can. Create a factory which returns the services you want and use that factory in your controllers to access the services. Ex.

var myapp = angular.module('myapp', []);
myapp.service('service1', function() {
    this.test = function(){
        console.log("Inside service1 -->test");
        //alert("Inside service1 -->test")
    }

});
myapp.service('service2', function() {
    this.test = function(){
        console.log("Inside service2 -->test");
        //alert("Inside service2 -->test");
    }

});
myapp.factory('servicesFactory', function(service1,service2) {
    return {
        service1 : service1,
        service2 : service2        
        };

});


myapp.controller('Ctrl', function ($scope,servicesFactory) {
    servicesFactory.service1.test();
    servicesFactory.service2.test();

});

Upvotes: 2

Related Questions