将表单重置为原始状态(AngularJS 1.0.x)

Rob*_*ink 63 angularjs

将表单字段重置为原始状态(重置脏状态)的功能在AngularJS 1.1.x的路线图中.不幸的是,目前的稳定版本缺少这样的功能.

将所有表单字段重置为AngularJS 1.0.x的初始原始状态的最佳方法是什么?

我想知道这是否可以通过指令或其他简单的解决方法来解决.我更喜欢解决方案,而无需触及原始的AngularJS源.为了澄清和证明这个问题,链接到JSFiddle.http://jsfiddle.net/juurlink/FWGxG/7/

想要的功能在路线图上 - http://blog.angularjs.org/2012/07/angularjs-10-12-roadmap.html
功能请求 - https://github.com/angular/angular.js/issues/856
建议的解决方案Pull请求 - https://github.com/angular/angular.js/pull/1127

更新了可能的解决方法

足够好的解决方法?

我只是想通了我可以重新编译HTML部分并将其重新放入DOM中.它的工作原理很适合临时解决方案,但也可以在评论中提到@blesh:

控制器应仅用于业务逻辑,而不是DOM!

<div id="myform">
  <form class="form-horizontal" name="form">
  </form>
</div>
Run Code Online (Sandbox Code Playgroud)

在我的控制器上resetForm():

  • 保存原始未触动的HTML
  • 重新编译保存的原始HTML
  • 从DOM中删除当前表单
  • 将新编译的模板插入DOM

JavaScript:

var pristineFormTemplate = $('#myform').html();
$scope.resetForm = function () {
    $('#myform').empty().append($compile(pristineFormTemplate)($scope));
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*ley 85

我认为值得一提的是,在Angular的后续版本(例如1.1.5)中,您可以调用$setPristine表单.

$scope.formName.$setPristine(true)
Run Code Online (Sandbox Code Playgroud)

这会将所有表单控件设置为原始状态.

的FormController.$ setPristine


小智 32

没有解决方法的解决方案

我想出了一个使用AngularJS的解决方案,没有任何解决方法.这里的技巧是使用AngularJS能力具有多个具有相同名称的指令.

正如其他人提到的那样,实际上有一个拉取请求(https://github.com/angular/angular.js/pull/1127),它使其进入AngularJS 1.1.x分支,允许重置表单.对此pull请求的提交改变了ngModel和form/ngForm指令(我本来希望添加一个链接,但Stackoverflow不希望我添加两个以上的链接).

我们现在可以定义我们自己的ngModel和form/ngForm指令,并使用pull请求中提供的功能扩展它们.

我已将这些指令包装在名为resettableForm的AngularJS模块中.您所要做的就是将此模块包含在您的项目中,并且您的AngularJS版本1.0.x就像在这方面的Angular 1.1.x版本一样.

''一旦你更新到1.1.x,你甚至不需要更新你的代码,只需删除模块,你就完成了!''

此模块还会将添加到1.1.x分支的所有测试传递给表单重置功能.

您可以在我创建的jsFiddle(http://jsfiddle.net/jupiter/7jwZR/1/)中看到该模块的示例.

第1步:在项目中包含resettableform模块

(function(angular) {

// Copied from AngluarJS
function indexOf(array, obj) {
  if (array.indexOf) return array.indexOf(obj);

  for ( var i = 0; i < array.length; i++) {
    if (obj === array[i]) return i;
  }
  return -1;
}

// Copied from AngularJS
function arrayRemove(array, value) {
  var index = indexOf(array, value);
  if (index >=0)
    array.splice(index, 1);
  return value;
}

// Copied from AngularJS
var PRISTINE_CLASS = 'ng-pristine';
var DIRTY_CLASS = 'ng-dirty';

var formDirectiveFactory = function(isNgForm) {
    return function() {
        var formDirective = {
            restrict: 'E',
            require: ['form'],
            compile: function() {
                return {
                    pre: function(scope, element, attrs, ctrls) {
                        var form = ctrls[0];
                        var $addControl = form.$addControl;
                        var $removeControl = form.$removeControl;
                        var controls = [];
                        form.$addControl = function(control) {
                            controls.push(control);
                            $addControl.apply(this, arguments);
                        }
                        form.$removeControl = function(control) {
                            arrayRemove(controls, control);
                            $removeControl.apply(this, arguments);
                        }
                        form.$setPristine = function() {
                            element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
                            form.$dirty = false;
                            form.$pristine = true;
                            angular.forEach(controls, function(control) {
                                control.$setPristine();
                            });
                        }
                    },
                };
            },
        };
        return isNgForm ? angular.extend(angular.copy(formDirective), {restrict: 'EAC'}) : formDirective;
    };
}
var ngFormDirective = formDirectiveFactory(true);
var formDirective = formDirectiveFactory();
angular.module('resettableForm', []).
    directive('ngForm', ngFormDirective).
    directive('form', formDirective).
    directive('ngModel', function() {
        return {
            require: ['ngModel'],
            link: function(scope, element, attrs, ctrls) {
                var control = ctrls[0];
                control.$setPristine = function() {
                    this.$dirty = false;
                    this.$pristine = true;
                    element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
                }
            },
        };
    });
})(angular);
Run Code Online (Sandbox Code Playgroud)

第2步:在控制器上提供一个重置模型的方法

请注意,重置表单时必须重置模型.在您的控制器中,您可以写:

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

function MyCtrl($scope) {
    $scope.reset = function() {
        $scope.form.$setPristine();
        $scope.model = '';
    };
}
Run Code Online (Sandbox Code Playgroud)

第3步:在HTML模板中包含此方法

<div ng-app="myApp">
<div ng-controller="MyCtrl">
<form name="form">
    <input name="requiredField" ng-model="model.requiredField" required/> (Required, but no other validators)
    <p ng-show="form.requiredField.$errror.required">Field is required</p>
    <button ng-click="reset()">Reset form</button>
</form>
<p>Pristine: {{form.$pristine}}</p>
</div>
</dvi>
Run Code Online (Sandbox Code Playgroud)


Ben*_*esh 7

编辑...我正在删除我的旧答案,因为它不够.

我实际上只是遇到了这个问题,这是我的解决方案:我为角度做了一个扩展方法.我通过跟随$ scope.form.$ setValidity()正在做的事情(反过来)来做到这一点......

这是一个实际的plnkr演示

这是我制作的辅助方法.这是一个黑客,但它的工作原理:

angular.resetForm = function (scope, formName, defaults) {
    $('form[name=' + formName + '], form[name=' + formName + '] .ng-dirty').removeClass('ng-dirty').addClass('ng-pristine');
    var form = scope[formName];
    form.$dirty = false;
    form.$pristine = true;
    for(var field in form) {
      if(form[field].$pristine === false) {
        form[field].$pristine = true;
      }
      if(form[field].$dirty === true) {
        form[field].$dirty = false;
      }
    }
    for(var d in defaults) {
      scope[d] = defaults[d];
    }
};
Run Code Online (Sandbox Code Playgroud)

希望这对某人有帮助.