Angular: how to extend a controller without using $ scope?
if you want to use the controller in the recommended "controller" how is the way?
lets skip this part where extending a controller is bad practice, I still believe there are cases where it is reasonable and useful.
Wrestled with controller extension in angularjs for a while, came up with the same as here: Angular: Controller extension which I like best. we still have the parent as an angularjs regulator, which makes sense in inheriting the controller, i.e. it is not a service with a $ scope field, which is not a prototype, which most likely is not testable, it is not a simple js function / object - this is an angular controller we want to extend in angularjs controllers.
now the problem with this solution is one: what if we want to use it in the recommended "controller as" path without $ scope visibility? I couldn't find anything with this on the internet, tried to make my own:
// @ngInject
function ParentCtrl(Service, CommonService) {
var vm = this;
//...
// could be moved out to abstract extendable
vm.extendTo = function(child) {
// we need this reassignment to new vm reference,
// to use overriden/child members in common/parent methods.
vm = angular.extend(child, vm);
return vm;
};
}
angular.module('common').controller('ParentCtrl', ParentCtrl);
// @ngInject
function ChildCtrl($controller, SpecificService) {
var vm = $controller('ParentCtrl', {Service: SpecificService}).extendTo(this);
}
angular.module('child').controller('ChildCtrl', ChildCtrl);
please, I need your opinions on the possible pitfalls of this solution, suggestions on how to do it better, in alternative ways. thank.
source to share
No one has answered this question yet
Check out similar questions: