2015-05-15 26 views
3

當我在角度擴展控制器時,有沒有什麼辦法從「子類」函數調用「超類」控制器上的函數來覆蓋它?角控制器繼承/重載「超類」方法

爲了清晰 - 在Java中我會做:

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

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

,我想要做的角相當於 - 這是

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 
    } 
} 
+1

簡答:是(請參閱:http://stackoverflow.com/a/19670187/624590)。長答案(/意見):考慮mixin或工廠作爲幹你的代碼而不是擴展/繼承的手段。 – DRobinson

+0

但是爲了使你的嘗試工作,在覆蓋它之前將舊的函數藏在某處:'var superDoStuff = $ scope.doStuff; $ scope.doStuff = function(){superDoStuff();/*做更多的東西* /};' – DRobinson

回答

1

我wouldn'牛逼推薦這種模式,但作爲一個問題的答案,這裏是一個辦法做到這一點:

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,我想你可以寫,允許您使用超類的引用替代性的輔助服務實現更清潔。也許通過壓倒「這個」。例如:

$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); 
     }; 
    }; 
}); 
0

您可以使用$父

所以

$scope.$parent.doStuff() 
+3

不同種類的繼承。問題是試圖創建一個擁有所有其他控制器屬性的控制器,但可以用自己的(超類/子類風格)覆蓋它們,而不是嵌套在另一個控制器中的控制器(如您的答案所示)。 http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 – DRobinson

+0

@DRobinson - 正是。 – drewmoore