Within AngularJs, I have multiple controllers that share similar functions:
angular.module('myApp').controller(...){
function lockForm(id){
...
}
function releaseForm(id){
...
}
function dbError(e){
...
}
// and other repetitive tasks in each controller
}
The examples I've come across usually involve extending (mixing) properties from $scope and @this. Is there a way to extend the entire controller itself?
Thanks to Shushanth Pallegar, I managed to solve my problem. It might not be exactly what I was looking for, but it's definitely an improvement.
// base ctrl
angular.module('myApp').controller('baseViewCtrl', function ($scope, viewData) {
this.lockForm = function() {
viewData.isLoading = true;
};
// ... and more
});
// child ctrl
angular.module('myApp').controller('childCtrl', function ($scope) {
var viewData = {
// some data
};
// inherit 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();
...
}
});
It may look messy because I used @this sparingly throughout the code.
I'm considering using 'base' instead of @this to clarify that these are injected methods:
// child ctrl
angular.module('myApp').controller('childCtrl', function ($scope) {
var viewData = {
// some data
};
// inherit 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();
...
}