While working on a web project with AngularJS, I've observed that most of my form controllers share similar structures. For instance, the only difference between my login controller (as shown below) and a reset password controller is that instead of $scope.loginForm.$invalid
, I'd have $scope.resetForm.$invalid
. Additionally, I would be using ResetService
rather than AuthService
.
angular.module('app').controller('LoginCtrl', function ($scope, AuthService) {
// Form input data
$scope.formData = {};
// Check if submit process is ongoing
$scope.busy = false;
// Determine if form has been submitted
$scope.submitted = false;
// Attempt to submit form via AJAX
$scope.submit = function (actionUrl) {
$scope.busy = true;
$scope.submitted = true;
// If form is invalid, return without submitting
if ($scope.loginForm.$invalid) {
$scope.busy = false;
return;
}
// Submit data via AJAX
AuthService.login(actionUrl, $scope.formData).error(function () {
$scope.busy = false;
});
};
});
It's quite evident that this code repetition violates the DRY principle. I presume there must be an Angular functionality or design pattern to refactor out this common functionality?