programing

FormController에서 양식 제어 가져오기

instargram 2023. 4. 2. 09:44
반응형

FormController에서 양식 제어 가져오기

앵글의 등록된 제어장치를 통해JS폼기본적으로 $dirty 컨트롤을 모두 가져오려고 하지만 컨트롤 배열이 없습니다(Form Controller에는 컨트롤 자체를 포함하는 것 외에 여러 가지 다른 속성/기능이 있습니다(각각의 오브젝트로서).

제가 소스코드를 살펴봤는데요, 제가 보니까controlsForm Controller의 어레이가 바로 제가 찾고 있는 어레이가 바로 그 어레이입니다.이 값에 액세스하거나 FormController를 확장하여 이 값을 반환하는 함수를 포함할 수 있는 방법이 있습니까?controls어레이?

편집: Pnkr 데모

또한 기술적으로 키 문자열의 첫 글자를 $로 확인할 수 있다는 것을 깨달았습니다만, 향후 Angular 버전에서 Form Controller/direction이 변경되는 경우는 피하고 싶습니다.

편집 2: 다른 설명:이 모든 것의 목표는 컨트롤 목록 전체를 루프함으로써 $dirty, $invalid, $error, $name을 제외한 $dirty, $dirty, $invalid, $error, $name,Form 객체에 존재하는 기타 속성) 또는 FormController를 확장하고 현재 더러운 컨트롤(시작값과 동일하지 않음)만 반환하는 함수를 만듭니다.

편집 3: 원하는 솔루션은 다양한 구조의 폼/모델에 적용할 수 있어야 합니다.스코프상의 모델은 AJAX 경유로 생성되어 있기 때문에, 그 구조는 이미 설정되어 있습니다(이미 AJAX 경유로 수신하고 있는 모든 데이터에 대해서 새로운 구조를 하드 코드 할 필요는 없습니다).또한 이 폼 제출 프로세스를 여러 폼/모델에 걸쳐 사용하려고 합니다.각 폼/모델은 오브젝트 모델의 다른 엔티티에 적용되므로 각각 다른 JSON 구조를 가지고 있습니다.이 때문에 제가 이 컴퓨터에 접근할 수 있는 방법을 물어본 겁니다controls[FormController]의 오브젝트 (코드를 게시합니다)FormController아래)는 모든 분야를 평평하게 배열할 수 있는 유일한 장소이기 때문입니다.

function FormController(element, attrs) {


var form = this,
      parentForm = element.parent().controller('form') || nullFormCtrl,
      invalidCount = 0, // used to easily determine if we are valid
      errors = form.$error = {},
      controls = [];

  // init state
  form.$name = attrs.name || attrs.ngForm;
  form.$dirty = false;
  form.$pristine = true;
  form.$valid = true;
  form.$invalid = false;

  parentForm.$addControl(form);

  // Setup initial state of the control
  element.addClass(PRISTINE_CLASS);
  toggleValidCss(true);

  // convenience method for easy toggling of classes
  function toggleValidCss(isValid, validationErrorKey) {
    validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
    element.
      removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
      addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
  }

  /**
   * @ngdoc function
   * @name ng.directive:form.FormController#$addControl
   * @methodOf ng.directive:form.FormController
   *
   * @description
   * Register a control with the form.
   *
   * Input elements using ngModelController do this automatically when they are linked.
   */
  form.$addControl = function(control) {
    controls.push(control);

    if (control.$name && !form.hasOwnProperty(control.$name)) {
      form[control.$name] = control;
    }
  };

  /**
   * @ngdoc function
   * @name ng.directive:form.FormController#$removeControl
   * @methodOf ng.directive:form.FormController
   *
   * @description
   * Deregister a control from the form.
   *
   * Input elements using ngModelController do this automatically when they are destroyed.
   */
  form.$removeControl = function(control) {
    if (control.$name && form[control.$name] === control) {
      delete form[control.$name];
    }
    forEach(errors, function(queue, validationToken) {
      form.$setValidity(validationToken, true, control);
    });

    arrayRemove(controls, control);
  };

  // Removed extra code
}

보다시피 양식 자체에는controls어레이를 비공개로 사용할 수 있습니다.제가 어떻게 더 연장할 방법이 있을까요?FormController그건 건개 ?? ?? ???아니면 적어도 개인 어레이를 볼 수 있도록 공용 기능을 만들까요?

질문에 대한 직접적인 해답을 얻으려면 @lombardo의 답변을 다음과 같이 수정하십시오.

     var dirtyFormControls = [];
     var myForm = $scope.myForm;
     angular.forEach(myForm, function(value, key) {
         if (typeof value === 'object' && value.hasOwnProperty('$modelValue') && value.$dirty)
             dirtyFormControls.push(value)                        
     });

그러면 'dirty Form Controls' 배열에는 더러운 폼 컨트롤이 포함됩니다.

또한 이 방법을 사용하여 양식 제출 시 '필수' 유효성 검사 및 기타 모든 항목에 대한 오류 메시지를 표시할 수 있습니다.submit() 함수에서는 다음과 같은 작업을 수행합니다.

 if (form.$invalid) {
     form.$setDirty();              
     angular.forEach(form, function(value, key) {
         if (typeof value === 'object' && value.hasOwnProperty('$modelValue'))
             value.$setDirty();                        
     });
    //show user error summary at top of form.
     $('html, body').animate({
         scrollTop: $("#myForm").offset().top
     }, 1000);
     return;
 }

그리고 당신의 양식에서 다음 오류 메시지가 나타납니다.

    <span ng-messages="myForm['subject-' + $index].$error" ng-show="myForm['subject-' + $index].$dirty" class="has-error">
        <span ng-message="required">Course subject is required.</span>
    </span>

위의 솔루션은 'ng-repeat' 등을 사용하여 동적으로 컨트롤을 생성하는 경우에 유용합니다.

다음 코드를 사용하여 컨트롤을 반복할 수 있습니다.

    var data = {};
    angular.forEach(myForm, function (value, key) {
        if (value.hasOwnProperty('$modelValue'))
            data[key] = value.$modelValue;
    });

컨트롤러 내에서 간단하게 시험해 보겠습니다.

$scope.checkForm = function(myFormName){
     console.log(myFormName.$invalid);
}

갱신:

<div ng-controller="MyController">
                <form name="form" class="css-form" novalidate>
                    <input type="text" ng-model="user.uname" name="uname" required /><br />
                    <input type="text" ng-model="user.usurname" name="usurname" required /><br />
                    <button ng-click="update(form)">SAVE</button>
                </form>
              </div>

app.controller('MyController',function($scope){
                $scope.user = {};
                $scope.update = function (form){
                    var editedFields = [];
                    angular.forEach($scope.user, function(value, key){
                        if(form[key].$dirty){
                           this.push(key + ': ' + value); 
                        }

                    }, editedFields);
                    console.log(editedFields);
                }
        });

어느 정도 괜찮은 해결책을 생각해 냈지만, 여전히 제가 찾던 방법이 아니에요.문자열에서 JSON 오브젝트를 작성하는 것과 관련된 다른 문제에서 몇 가지 코드를 제거하고 다음을 생각해냈습니다.

기본적으로 모델에 연결된 것과 동일한 방식으로 필드에 이름을 지정하고 form_submit이 호출될 때 제출할 새 개체를 만듭니다.

Pnkr

데모에서 양식 필드 중 하나를 변경한 다음 제출을 누르면 더티 값만 표시된 개체가 표시됩니다.

언급URL : https://stackoverflow.com/questions/20908096/getting-form-controls-from-formcontroller

반응형