整个表单的类似 ngChange 的功能 [英] ngChange-like functionality for the entire form
问题描述
每当表单的一个输入字段发生变化时,我都想对整个表单执行等效的 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
事件会在元素值更改时发送到元素.此事件仅限于 元素、
框和
元素.对于选择框、复选框和单选按钮,当用户使用鼠标进行选择时会立即触发该事件,但对于其他元素类型,该事件会推迟到该元素失去焦点为止.
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屋!