整个表单的类似ngChange的功能 [英] ngChange-like functionality for the entire form

查看:79
本文介绍了整个表单的类似ngChange的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当其中一个输入字段发生变化时,我都希望对整个表单执行ng-change的等效操作.

I would like to do an equivalent of ng-change for the entire form whenever there is a change in one of its input fields.

我知道自AngularJS 1.3起,我具有debounce选项,但它仅适用于单个输入.

I know that since AngularJS 1.3 I have the debounce option but it applies only for a single input.

我正在寻找适用于整个表格的反跳"/更改时"功能.

I'm looking for a "debounce"/"on change" functionality that will apply for the entire form.

推荐答案

没有内置的方法可以对表单进行ng-change.

There isn't a built-in way to do ng-change for a form.

甚至不需要,因为如果您正确组织了视图模型,则表单输入很可能会绑定到某个范围暴露的属性:

It may not even be needed, because if you organized your view model properly, then your form inputs are likely bound to a certain scope-exposed property:

$scope.formData = {};

并在视图中:

<form name="form1">
  <input ng-model="formData.a">
  <input ng-model="formData.b">
</form>

然后,您可以深入观察(使用$watch)模型更改(并在所需的元素上应用任何反跳选项):

Then you could deep-watch (with $watch) for model changes (and apply whatever debounce option on elements that you need):

$scope.$watch("formData", function(){
  console.log("something has changed");
}, true);

然后,问题是,当然,这是一本精打细算的书,而且价格昂贵.此外,它不仅对表单中的更改做出反应,而且还对任何来源中的formData中的更改做出反应.

Then problem is, of course, that this is a deep-watch and it is expensive. Also, it reacts not only to changes in the Form, but also to a change in formData from any source.

因此,作为替代方案,您可以创建自己的指令来补充表格并对表格的更改事件做出反应.

So, as an alternative, you could create your own directive to compliment the form and react to form's change events.

.directive("formOnChange", function($parse){
  return {
    require: "form",
    link: function(scope, element, attrs){
       var cb = $parse(attrs.formOnChange);
       element.on("change", function(){
          cb(scope);
       });
    }
  }
});

,用法是:

<form name="form1" form-on-change="doSomething()">
  <input ng-model="formData.a">
  <input ng-model="formData.b">
</form>

plunker 进行说明.

请注意,根据 jQuery文档,

change事件在其值更改时发送到元素.此事件仅限于<input>元素,<textarea>框和<select>元素.对于选择框,复选框和单选按钮,当用户使用鼠标进行选择时会立即触发该事件,但是对于其他元素类型,该事件将推迟到该元素失去焦点之前.

The change event is sent to an element when its value changes. This event is limited to <input> elements, <textarea> boxes and <select> elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

这篇关于整个表单的类似ngChange的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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