如何引用AngularJS创建的表单字段

时间:2015-11-02 16:54:01

标签: 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;

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

1 个答案:

答案 0 :(得分:3)

如果您希望能够引用表单中的字段,则可以为字段提供name属性。默认情况下会生成name。这是角度形式提供的好东西之一(你不必考虑它)。但是如果你想直接用特定的key引用它(就像你一样)那么你最好自己提供一个。

所以你会做这样的事情:

$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)
      })
    }
  })
}

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