AngularJs.$ setPristine重置表单

Pir*_*ada 74 angularjs

提交表单后,我一直在努力重置表单.有人发布了这里我想让它工作但没有成功.这是我的代码示例.

$scope.form.$setPristine();没有设置Pristine: {{user_form.$pristine}}true.见上面的例子.

Luc*_*olt 89

$ setPristine()是在angularjs的1.1.x分支中引入的.您需要使用该版本而不是1.0.7才能使其正常工作.

请参阅http://plnkr.co/edit/815Bml?p=preview


小智 15

有一个类似的问题,我不得不将表单设置回pristine,但也没有触及,因为$ invalid和$ error都用于显示错误消息.仅使用setPristine()不足以清除错误消息.

我通过使用setPristine()和setUntouched()解决了它.(参见Angular的文档:https://docs.angularjs.org/api/ng/type/ngModel.NgModelController)

所以,在我的控制器中,我用过:

$scope.form.setPristine(); 
$scope.form.setUntouched();
Run Code Online (Sandbox Code Playgroud)

这两个函数将完整的表单重置为$ pristine并返回到$ untouched,以便清除所有错误消息.

  • 谢谢(你的)信息.在我的例子中,它是form.$ setPristine()和form.$ setUntouched(). (6认同)

Dav*_*Lin 12

只为那些想要$setPristine无需升级到v1.1.x的人,这里是我用来模拟$setPristine函数的函数.我不愿意使用v1.1.5,因为我使用的AngularUI组件之一是不兼容的.

var setPristine = function(form) {
    if (form.$setPristine) {//only supported from v1.1.x
        form.$setPristine();
    } else {
        /*
         *Underscore looping form properties, you can use for loop too like:
         *for(var i in form){ 
         *  var input = form[i]; ...
         */
        _.each(form, function (input) {
            if (input.$dirty) {
                input.$dirty = false;
            }
        });
    }
};
Run Code Online (Sandbox Code Playgroud)

请注意,它仅使$dirty字段清洁并帮助更改"显示错误"条件,如$scope.myForm.myField.$dirty && $scope.myForm.myField.$invalid.

表单对象的其他部分(如css类)仍然需要考虑,但这解决了我的问题:隐藏错误消息.


vin*_*eet 7

通过将表单发送到控制器,还有另一种原始形式的方法.例如:-

在视图中: -

<form name="myForm" ng-submit="addUser(myForm)" novalidate>
    <input type="text" ng-mode="user.name"/>
     <span style="color:red" ng-show="myForm.name.$dirty && myForm.name.$invalid">
      <span ng-show="myForm.name.$error.required">Name is required.</span>
    </span>

    <button ng-disabled="myForm.$invalid">Add User</button>
</form>
Run Code Online (Sandbox Code Playgroud)

在控制器: -

$scope.addUser = function(myForm) {
       myForm.$setPristine();
};
Run Code Online (Sandbox Code Playgroud)


小智 6

DavidLn的答案在过去对我有用.但它并没有捕获setPristine的所有功能,这次让我绊倒了.这是一个更完整的垫片:

var form_set_pristine = function(form){
    // 2013-12-20 DF TODO: remove this function on Angular 1.1.x+ upgrade
    // function is included natively

    if(form.$setPristine){
        form.$setPristine();
    } else {
        form.$pristine = true;
        form.$dirty = false;
        angular.forEach(form, function (input, key) {
            if (input.$pristine)
                input.$pristine = true;
            if (input.$dirty) {
                input.$dirty = false;
            }
        });
    }
};
Run Code Online (Sandbox Code Playgroud)