javascript - 如何正式引用AngularJS创建的表单字段

标签 javascript angularjs angular-formly

我使用 Formly 在 angularJS 中创建表单

这是我的领域

$scope.postFields = [
    {
        key: 'title',
        type: 'input',
        templateOptions: {
            label: "Title",
            // required: true,
            minlength: 2,
        },
        validation: {
            messages: {
                required: function(viewValue, modelValue, scope) {
                    return scope.to.label + ' is required'
                }
            }
        }
    }
]

我正在尝试按如下方式访问我的字段

    function failure(response) {
    console.log("failure", response)

    _.each(response.data, function(errors, key) {
        _.each(errors, function(e) {
            $scope.form[key].$dirty = true;
            $scope.form[key].$setValidity(e, false);
        });
    });
}

我的正式形式

<formly-form form="postForm" model="model" fields="postFields" class="col-md-4">
    <button type="submit" class="btn btn-primary" ng-click="addPost()">Submit</button>
</formly-form>

但是我当然收到了这个错误:

TypeError: Cannot read property 'title' of undefined

就在这条线上

$scope.form[key].$dirty = true;

你们中有人知道如何以正确的方式引用创建的正式字段吗?

最佳答案

如果您希望能够引用表单中的字段,您可以为字段提供 name 属性。 名称是默认生成的。这是 Angular-formly 提供的好东西之一(你不必考虑它)。但是,如果您想使用特定的直接引用它(就像您一样),那么您最好自己提供一个。

所以你会做这样的事情:

$scope.postFields = [
    {
        key: 'title',
        name: 'title',
        type: 'input',
        templateOptions: {
            label: "Title",
            // required: true,
            minlength: 2,
        },
        validation: {
            messages: {
                required: function(viewValue, modelValue, scope) {
                    return scope.to.label + ' is required'
                }
            }
        }
    }
]

或者,您可以创建 fieldTransform自动执行此操作(只需指定与键相同的名称)。或者在错误处理程序中,您可以从字段的 formControl 查找 NgModelController像这样的属性:

function handleError(fields, response) {
  _.each(fields, function(field) {
    if (response.data[field.key]) {
      field.formControl.$setDirty()
      _.each(response.data[field.key], function(e) {
        field.formControl.$setValidity(e, false)
      })
    }
  })
}

这可能是最好的解决方案:-)祝你好运!

关于javascript - 如何正式引用AngularJS创建的表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33482829/

相关文章:

javascript - 嵌套 HTML 元素的 Angular 范围问题

javascript - Angular 应用程序中默认日期到 JSON 转换格式

javascript - 如何向链接函数注入(inject)服务?

javascript - 我应该使用 window.webkitRequestAnimationFrame 而不是 setInterval 吗?

javascript - 更新 React Js 中的对象数组

angularjs - 单元测试时如何在 Angular 1.5 中向 $componentController 添加依赖项

javascript - JS : use grunt + mocha + phantomjs

javascript - 在文本字段内显示数量值

javascript - Angular 示例代码不起作用