当我以 Angular 扩展 Controller 时,有没有办法从覆盖它的“子类”函数调用“父类(super class)” Controller 上的函数?
为清楚起见——在 Java 中我会这样做:
class Foo {
void doStuff(){
//do stuff
}
}
class FooBar extends Foo {
void doStuff(){
super.doStuff();
//do more stuff
}
}
我想在 Angular 上做同样的事情-一些
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
}
}
最佳答案
我不推荐这种模式,但作为问题的答案,这里有一种方法可以做到:
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();
}
}
}
废话,我想你可以编写一个帮助服务,允许你使用对父类(super class)实现的引用来覆盖属性,以使其更清晰。也许通过覆盖“这个”。像这样的东西:
$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);
};
};
});
关于javascript - Angular Controller 继承/覆盖 "superclass"方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30250201/