简体   繁体   English

验证后角度形式重置

[英]Angular form reset after validation

I am using angular js for validation on form its working fine but after form is valid i am sending ajax request and resting it with jquery code, So my form still shows valid. 我正在使用角度js进行验证,表单工作正常,但在表单有效后我发送ajax请求并使用jquery代码保留它,所以我的表单仍然显示有效。 Here is following js snippet: 这是以下js片段:

var myApp = angular.module('myApp', []);

myApp.controller('myController', function ($scope) {    

    $scope.clearForm = function (formId) {
        $(formId)[0].reset();
        console.log($scope.note['title'])
        //$scope.note['title'] = null;
    };

    $scope.submitForm = function () {
        if ($scope.noteForm.$valid) {
            alert("valid");
            //ajax request
            $scope.clearForm('#noteForm');
        }
    }
});

Fiddle Demo 小提琴演示

If i am setting blank value with $scope.note['title'] = null; 如果我用$scope.note['title'] = null;设置空白值$scope.note['title'] = null; it shows error after clearing. 清除后显示错误。

Fiddle Demo 小提琴演示

How can i resolve this? 我该如何解决这个问题? what i want is after resting from should goes to initial state. 我想要的是休息后应该进入初始状态。

Rather than clearing form in jQuery, I'd prefer you to use $setPristine() method on form that will make form as pristine in angular way. 而不是在jQuery中清除表单,我宁愿你在form上使用$setPristine()方法,这将使表单成为一个pristine的角度方式。 Also you need to clear form fields just by doing $scope.note = {} . 您还需要通过执行$scope.note = {}来清除表单字段。

Code

$scope.clearForm = function (formId) {
    $scope.noteForm.$setPristine(); //you should use setPristine that will make for pristine
    $scope.note = {}; //this will clear a form values.
};

Demo Fiddle 演示小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM