在 angularJs 中,我有一堆具有相同功能的 Controller :
angular.module('myApp').controller(...){
function lockForm(id){
...
}
function releaseForm(id){
...
}
function dbError(e){
...
}
// and some other little stuff again and again in every controller
}
我读过的例子都是基于扩展(mixin)来自$scope 和@this 的东西。没有办法按原样扩展整个 Controller 吗?
感谢Shushanth Pallegar我解决了我的问题。这不是我想要的,但比以前好多了。
// base ctrl
angular.module('myApp').controller('baseViewCtrl', function ($scope, viewData) {
this.lockForm = function() {
viewData.isLoading = true;
};
// ... and others
});
// child ctrl
angular.module('myApp').controller('childCtrl', function ($scope) {
var viewData = {
// some stuff
};
// inject from basecontroller
angular.extend(this, $controller('baseViewCtrl', {$scope: $scope, viewData: viewData}));
// link $scope
$scope.viewData = viewData;
$scope.onSelectUnit = onSelectUnit;
// child controller methods
function onSelectUnit(){
this.lockForm();
...
}
});
它看起来有点难看,因为我几乎在所有地方都避免使用@this
也许我这样做并使用 base 而不是 @this 来更清楚地表明存在注入(inject)方法:
// child ctrl
angular.module('myApp').controller('childCtrl', function ($scope) {
var viewData = {
// some stuff
};
// inject from basecontroller
var base = $controller('baseViewCtrl', {$scope: $scope, viewData: viewData});
// link $scope
$scope.viewData = viewData;
$scope.onSelectUnit = onSelectUnit;
// child controller methods
function onSelectUnit(){
base.lockForm();
...
}
最佳答案
使用 $controller 服务并传递您需要扩展的 Controller 的名称,如下所示
父 Controller
angular.module('myApp').controller('parentController',function(){
$scope.lockForm = function(id){
...
}
});
子 Controller
angular.module('app').controller('childController',function($controller){
var parentController = $controller('parentController',{$scope:$scope});
console.log(parentController.lockForm);
});
为了扩展到 this
,使用如下
angular.module('app').controller('childController',function($controller){
var parentController = $controller('parentController',{$scope:$scope});
angular.extend(this,parentController);
console.log(this.lockForm);
});
如果您使用函数并将它们附加到作用域,则需要按如下方式返回这些函数。
angular.module('myApp').controller('parentController',function(){
var _lockForm = function(id){
...
}
return{
lockForm = _lockForm
}
});
所以在你的扩展 Controller 中可以像下面这样使用
var extendedController = $controller('parentController',{$scope:$scope});
extendeController.lockForm('123');
关于javascript - Angular 扩展 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37633738/