gpt4 book ai didi

javascript - 使用 Angular 时表单元素是否需要 name 属性?

转载 作者:搜寻专家 更新时间:2023-11-01 05:04:51 25 4
gpt4 key购买 nike

我现在使用 Angular JS 进行所有表单管理。输入数据存储到它们关联的 ngModel 中,可以在 controller$scope 中处理。

所以我有这样的表单设置:

<form name="addJob" novalidate data-ng-submit="addJob.$valid && addJob(job)">
<input type="text" placeholder="Job Title" data-ng-model="job.title" required />
<textarea placeholder="Brief" data-ng-model="job.brief"></textarea>
<button type="submit" data-ng-disabled="addJob.$invalid">Add Job</button>
</form>

这在所有主要浏览器中都工作得很好(除了我没有测试过 IE)。您会注意到我没有在输入或文本区域中包含名称属性。我出于任何原因需要它们吗?我以前读过以下内容:

Note: Only form elements with a name attribute will have their values passed when submitting a form. 

但是我的数据传递得非常好,因为它绑定(bind)到 ngModel。是正确的方法 - 包括还是不包括名称属性?

最佳答案

您需要元素上的 name 属性以及 ng-model 以便将实例添加到 formController 以及在控件或表单上进行任何验证。此外,如果您正在提交表单(表单上的操作),则只有具有 name 属性的表单元素才会提交给服务器。查看native form validation and submission process .

在 ngModelController 实例中有一个名为 $name 的属性,它只是元素的名称。

ngModelController source

this.$name = $attr.name; 

并且 ng-model 指令在其父 formcontroller 实例(如果存在)上调用 $addControl 方法,该实例将实例添加为具有 name 的键的值formController 实例,如果您没有名称,那么它不会被关联,并且不会发生 Angular 验证。

FormController Source

form.$addControl = function(control) {
// Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
// and not added to the scope. Now we throw an error.
assertNotHasOwnProperty(control.$name, 'input');
controls.push(control);

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

因此,在您的情况下,如果您不依赖 Angular 表单 Controller 验证或不提交带有操作的表单,则不需要名称

关于javascript - 使用 Angular 时表单元素是否需要 name 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27849318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com