Extend Angular Controllers Using Controlleras Syntax & Prototypical Inheritance
I'm trying to extend controllers using conrollerAs syntax. My parent and child controllers are not defined in the same scope, so I put the parent controller (BaseController) in a s
Solution 1:
angular.injector
creates a new injector instance (which is application instance, if it sounds better) and shouldn't be used in production within Angular app. I.e.
angular.injector(['myApp']).get('BaseController') !== angular.injector(['myApp']).get('BaseController');
You need to put your hands on BaseController
dependency when you're still able to register controllers, and the only place for doing this is config phase,
angular.module('myApp').config(function($controllerProvider, BaseController) {
...
$controllerProvider.register('ChildController', ...)
});
This requires BaseController
to be constant
, not factory
, and possibly limits the things you would like to do with it. Sounds less funny, doesn't it?
So a better thing to do here is just
varChildController = function(BaseController, fooService, barService) {
angular.extend(this, BaseController.prototype, { ... });
BaseController.apply(this, [fooService, barService]);
}
angular.module('myApp').controller('ChildController', ChildController);
Angular DI isn't suited well for OOP JS for the reasons shown above and still needs to be supplemented with other modular solutions.
Post a Comment for "Extend Angular Controllers Using Controlleras Syntax & Prototypical Inheritance"