使用Angular Formly时,表单中未包含的空字段会提交

Osk*_*son 5 html javascript forms angularjs angular-formly

使用Angular Formly我已经设置了以下控制器和模板.我让控制器将用户输入的值打印到所有字段中,但用户未触摸的字段除外.这意味着如果用户在字段中根本不写任何内容,则不包括该字段.虽然如果用户输入内容然后将其删除,则该字段包含空字符串.

如何包含用户未触及的字段?

// fooController.js

vm.fooModel= {};
vm.fooFields = [
    {
        key: 'foo',
        type: 'input'
        templateOptions: {
            label: 'Foo',
            placeholder: 'Foo'
        }
    }
];

vm.onSubmit = function() {
    console.log(vm.fooModel)
}
Run Code Online (Sandbox Code Playgroud)
// fooTemplate.html

<form ng-submit="vm.onSubmit()" novalidate>
    <formly-form model="vm.fooModel" fields="vm.fooFields"></formly-form>
    <button type="submit" class="btn btn-info submit-button">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

我不希望将空字符串设置为每个字段的默认值.


这里有一个简单的例子

Vai*_*hah 0

每个 Angular js 字段都有以下状态

$untouched The field has not been touched yet
$touched The field has been touched
$pristine The field has not been modified yet
$dirty The field has been modified
$invalid The field content is not valid
$valid The field content is valid
Run Code Online (Sandbox Code Playgroud)

您可以查看帮助,$pristine该帮助表明输入字段未从原始值修改。

您甚至可以迭代 myForm 对象(非输入字段对象的键以 $ 为前缀),然后添加到您的 fooFields 对象中

angular.forEach($scope.myForm, function(value, key) {
  if(key[0] == '$') return;
       console.log(key, value.$pristine)
       if(value.$pristine){
         // add your field in fooFields object
       }
});
Run Code Online (Sandbox Code Playgroud)