DRY AngularJS Form Controllers

I use AngularJS in a web project and I notice that almost all of my form controllers look the same. The only difference is from the login controller (see below) and saying that my password controller reset $scope.loginForm.$invalidwill be equal $scope.resetForm.$invalid, and I would add and use ResetServiceinstead AuthService.

angular.module('app').controller('LoginCtrl', function ($scope, AuthService) {

  // Form input data
  $scope.formData = {};

  // Are we in the middle of a submit process?
  $scope.busy = false;

  // Has the form been submitted yet?
  $scope.submitted = false;

  // Attempt to submit form via AJAX
  $scope.submit = function (actionUrl) {

    $scope.busy = true;
    $scope.submitted = true;

    // Invalid, activate form and return
    if ($scope.loginForm.$invalid) {
      $scope.busy = false;
      return;
    }

    // Submit data via AJAX
    AuthService.login(actionUrl, $scope.formData).error(function () {
      $scope.busy = false;
    });

  };

});

Obviously this is not very DRY, and I assume there is an Angular function or template to extract this similar functionality?

+3
source share
2 answers

A FormCtrl . 2 , , - AJAX , , $scope. , , .

, LoginCtrl ( , ), - FormCtrl $scope, , , , AJAX.

login.html

<form ng-controller="LoginCtrl"
      ng-submit="submit('my-ajax-url.php')"
      name="loginForm">
  ...
</form>

FormCtrl.js

angular.module('app').controller('FormCtrl', function ($scope, formName, ajaxFunction) {

  // Form input data
  $scope.formData = {};

  // Are we in the middle of a submit process?
  $scope.busy = false;

  // Has the form been submitted yet?
  $scope.submitted = false;

  // Attempt to submit form via AJAX
  $scope.submit = function (actionUrl) {

    $scope.busy = true;
    $scope.submitted = true;

    // Invalid, activate form and return
    if ($scope[formName].$invalid) {
      $scope.busy = false;
      return;
    }

    // Submit data via AJAX
    ajaxFunction(actionUrl, $scope.formData).error(function () {
      $scope.busy = false;
    });

  };

});

LoginCtrl.js

angular.module('app').controller('LoginCtrl', function ($scope, $controller, AuthService) {

  // Instantiate form controller
  $controller('FormCtrl', {
    $scope: $scope,
    formName: 'loginForm',
    ajaxFunction: AuthService.login
  });

});
+1

, :

angular.module('app').controller('LoginCtrl', FUNCTION)

factory.

angular $injection , . :

functionName.$inject = ['$rootScope'];

angular, $rootScope. , .

angular.module('app')
    .controller(
        'LoginCtrl',
        ControllerFactory.createSubmitController(function(){}, ['$scope', 'AuthService'])
    )

createSubmitController - . $scope , , 1- , $scope.

, ​​ , .

factory, ​​, :

function($scope, AuthService)

.

. $inject

0

All Articles