Angular controller inheritance / overriding "superclass" methods
When I extend a controller in angular, is there a way to call the function on the "superclass" controller from the "subclass" function that overrides it?
For clarity - in Java I would do:
class Foo {
void doStuff(){
//do stuff
}
}
class FooBar extends Foo {
void doStuff(){
super.doStuff();
//do more stuff
}
}
and I would like to do the equivalent in angular - something
myApp.controller('FooCtrl', function($scope){
$scope.doStuff = function(){
//do stuff
}
}).controller('FooBarCtrl', function($scope){
angular.extend(this, $controller('FooCtrl', {$scope: $scope}));
$scope.doStuff = function(){
// ??? <- INSERT ANSWER HERE
//do more stuff
}
}
+3
source to share
2 answers
I wouldn't recommend this pattern, but as an answer to the question, here's how to do it:
myApp.controller('FooCtrl', function($scope){
$scope.doStuff = function(){
//do stuff
}
}).controller('FooBarCtrl', function($scope){
angular.extend(this, $controller('FooCtrl', {$scope: $scope}));
//extend the scope
var super = angular.extend({}, $scope);
$scope.doStuff = function(){
// ??? <- INSERT ANSWER HERE
//do more stuff
//call the "superclass" methods
if(super.doStuff){
super.doStuff();
}
}
}
Spitballing, I suppose you could write a helper service that would allow properties to be overridden with superclass references to make it cleaner. Perhaps by overriding "this". Something like:
$scope.doStuff = $override($scope.doStuff, function() {
this(); //calls the original doStuff function
});
.factory('$override', function(){
return function(method, func){
return function(){
return func.apply(method, arguments);
};
};
});
+1
source to share