如果表单控件具有无效数据,则$ setPristine()无法正常工作

时间:2014-02-26 01:19:32

标签: angularjs angularjs-directive angularjs-scope angular-ui

我正在尝试使用$ setPristine()重置表单。

$scope.resetDataEntryForm = function() {
    $scope.dataEntryForm.$setPristine();
    $scope.pr = {};
};

如果所有输入控件都处于有效状态,则它可以正常工作。其中一个输入类型是URL。例如,如果我点击重置时我的URL值无效。如果上面的代码重置URL输入字段的内容并将错误标记为false。我需要这个来进行验证。

要进行正确的重置,我必须手动重置所有错误标志

$scope.resetDataEntryForm = function() {
    $('#dataEntryForm')[0].reset();
    $scope.dataEntryForm.$setPristine();
    $scope.dataEntryForm.name.$error.required = true;
    $scope.dataEntryForm.site.$error.required = true;
    $scope.dataEntryForm.site.$error.url = false;
    $scope.pr = {};
};

有人可以建议使用angular.js重置表单的正确方法吗?

1 个答案:

答案 0 :(得分:0)

我不知道是否有意,但$setPristine()不会更改$error个对象。

这是Form

上setPristine的源代码
    form.$setPristine = function () {
        element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
        form.$dirty = false;
        form.$pristine = true;
        forEach(controls, function(control) {
          control.$setPristine();
        });
      };

这是对Control(输入元素等)的代码调用

    this.$setPristine = function () {
      this.$dirty = false;
      this.$pristine = true;
      $element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
    };  

在我看来,您必须自己重置$error对象

PS:代码来自AngularJs版本1.2。*,您可以在Github上查看当前版本https://github.com/angular/angular.js/blob/291d7c467fba51a9cb89cbeee62202d51fe64b09/src/ng/directive/form.js