获取表单控件从的FormController [英] Getting form controls from FormController

查看:151
本文介绍了获取表单控件从的FormController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过AngularJS形式的注册控制的方式进行循环。从本质上讲,我试图让所有的$脏的控制,但没有控件数组(的的FormController有一些除了不同性能/功能包含控件本身 - 每一个为自己的对象)。

I need a way to loop through the registered controls of an AngularJS form. Essentially, I'm trying to get all the $dirty controls, but there's no array of the controls (the FormController has a number of different properties/functions in addition to containing the controls themselves - each as its' own object).

我一直期待在源$ C ​​$ C,我看到有一个控制数组中,这正是我要找的数组的FormController对于。是否有一种方式来获得进入此值,或延长的FormController包括返回此控制功能数组?

I've been looking at the source code, and I see that there is a controls array in the FormController that is exactly the array I'm looking for. Is there a way to get access to this value, or extend the FormController to include a function that returns this controls array?

编辑: Plnkr 演示

另外,我意识到,在技术上,我可以在角将来的版本为$的键值字符串检查的第一个字符,但我想,以避免万一的FormController /指令的变化。

Also, I realized that technically I could check the first character in the key string for "$", but I'd like to avoid that in case the FormController/directive changes in a future version of Angular.

编辑2:另一种澄清:我在所有这一切的目标是能够确定哪些特定字段是$脏,是否通过的控制整个列表循环(不包括$脏,$无效,$误差$名称,和其它性质生活在因为它是表格对象)或通过扩展的FormController并创建仅返回这是当前脏(和不等于其初始值的控制)的函数

Edit 2: Another clarification: My goal in all of this is to be able to determine which specific fields are $dirty, whether by looping through the entire list of controls (not including the $dirty, $invalid, $error, $name, and other properties that live in the Form object as it is) or by extending the FormController and creating a function that returns only the controls which are currently dirty (and not equal to their starting values)

编辑3:我在寻找需求的解决方案,适用于不同的结构形式/模型。示波器上的模型是通过AJAX生成的,因此它们的结构已经被设置(我想避免硬code一个新的结构,所有的数据,我通过AJAX已经收到)。另外,我也希望在多个表格/机型使用这种形式提交过程中,和他们每个人都有不同的JSON结构 - 因为它们适用于不同的实体,我们的对象模型。这就是为什么我选择索要一种方式来获得进入控制对象中的FormController(我会后从<$ C $的code C>的FormController 以下),因为它是在那里我能得到我所有的字段的平面阵列的唯一地方。

Edit 3: The solution I'm looking for needs to be applicable to forms/models of different structures. The models on the scope are generated via AJAX, so their structure is already set (I'd like to avoid having to hardcode a new structure for all the data I'm already receiving via AJAX). Also, I'm looking to use this form submission process across multiple forms/models, and each of them have differing JSON structures - as they apply to different entities in our Object Model. This is why I've chosen to ask for a way to get access to the controls object in the FormController (I'll post the code from FormController below), because it's the only place where I can get a flat array of all of my fields.

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
}

正如你所看到的,形式本身所具有的控制阵列私下使用。我不知道是否有一种方法对我来说,延长的FormController 这样我就可以使该对象公开?或创建一个公共函数,所以我至少可以查看私有数组?

As you can see, the form itself has the controls array privately available. I'm wondering if there's a way for me to extend the FormController so I can make that object public? Or create a public function so I can at least view the private array?

推荐答案

对于直接解决问题的办法,修改@隆巴多的回答像这样;

For a direct solution to the question, modify @lombardo's answer like so;

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

该阵列'dirtyFormControls'然后将包含脏了。

The array 'dirtyFormControls' will then contain the form controls that are dirty.

您也可以使用这一招对表单提交的必需验证和所有其他显示错误消息。在你提交()函数,你会做这样的事情;

You can also use this trick to show error messages on form submission for 'Required' validations and all others. In your submit() function you will do something like;

 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;
 }

而在你的表格,你会显示错误消息

And in your form you will show error messages with

    <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重复或类似的东西。

The above solution is useful when you have dynamically generated controls using 'ng-repeat' or something similar.

这篇关于获取表单控件从的FormController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆