drew moore
drew moore

Reputation: 32680

Angular controller inheritance / overriding "superclass" methods

When I extend a controller in angular, is there any way to call a function on the "superclass" controller from a "subclass" function that overrides it?

For clarity - in Java I'd do:

class Foo {
    void doStuff(){
        //do stuff 
    }
} 

class FooBar extends Foo {
     void doStuff(){
         super.doStuff();
         //do more stuff
     }
}

and I'd 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
     }
}

Upvotes: 3

Views: 4112

Answers (2)

Joe Enzminger
Joe Enzminger

Reputation: 11190

I wouldn't recommend this pattern, but as an answer to the question, here is a way 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 of you could write a helper service that allowed you to override properties with references to the superclass implementations 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);
        };
    };
});

Upvotes: 1

kwangsa
kwangsa

Reputation: 1711

You can use $parent

so

$scope.$parent.doStuff()

Upvotes: 0

Related Questions