Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I am trying to create a set of Controller classes which are derived from a base class that have many dependencies. Every time I want to create a derived class I have to copy the base class constructor dependencies into the derived class constructor. This seems particularly ugly and repetitive. See below;

module MyModule
{    
     export class ParentCtrl
     {
         constructor($http, $provide, $scope,$compile,MyService,$parse,$timeout)
         {
             console.log('parent');
         }

         FunctionA(){...}
         ...
         FunctionZ(){...}
     }

     export class ChildCtrl extends ParentCtrl
     {
         constructor($http, $provide, $scope,$compile,MyService,$parse,$timeout)
         {
           super($http, $provide, $scope,$compile,MyService,$parse,$timeout);
           console.log('child');
         }
         FunctionA(){ console.log('Override A'); }
     }

     export class GrandChildCtrl extends ChildCtrl
     {
         constructor($http, $provide, $scope,$compile,MyService,$parse,$timeout)
         {
           super($http, $provide, $scope,$compile,MyService,$parse,$timeout);
           console.log('grandchild');
         }
         FunctionB(){ console.log('Override B'); }
     }
 }

I have removed the type definitions from the constructor parameters for ease of reading.

Is there a way to avoid these lengthy constructor being duplicated? I had thought of having a function in the base/Parent controller which is called from the constructor to inject the required types. This would mean dependencies would be confined to the base class.

Has anyone successfully tried this before?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Angular is not friendly to controller inheritance. It favors composition. Consider factoring out the utility code into an Angular Service : https://docs.angularjs.org/guide/services (which are singletons) or just another typescript utility class.

If you must you could just inject the $injector in the base : https://docs.angularjs.org/api/auto/service/$injector and use that to load what you need inside the base constructor.

share|improve this answer
    
Basarat many thanks for your feedback. The $injector is the preferred approach for which I have not been able to get the $injector to work. I've not been sure how to get the correct injector in attempts so far. Also do you foresee any problems with this approach? –  devman81 Aug 22 '14 at 13:27
    
You can get $injector same as e.g. $http. Foresee : if it works for you go for it :) –  basarat Aug 22 '14 at 22:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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