【问题标题】:Angular: Reset Form FunctionAngular:重置表单功能
【发布时间】:2015-01-20 14:22:12
【问题描述】:

我设置了一个功能来重置我页面上的表单。当我点击“重置”按钮时,它.$setPristine() 的表单并清除了titleaddressphonelinks 字段。

function resetForm() {
  $scope.entryForm.$setPristine();
  $scope.title = '';
  $scope.address = {};
  $scope.phone = '';
  $scope.links = {};
}

问题是,我实际上在该页面上有几个不同的表单,它们具有不同的输入字段。

我没有编写几个重置函数,而是想知道是否有一种方法可以创建一个更通用的重置函数,在运行时将表单设置为.$setPristine() 并重置所有字段?

对此的任何帮助表示赞赏。提前致谢!

【问题讨论】:

    标签: javascript jquery angularjs forms


    【解决方案1】:

    更好的方法是声明 resetDirective 并使用它来恢复它的形式 初始状态

    myApp.directive( 'resetDirective', [ '$parse', function ( $parse ) {
        return function( scope, element, attr ) {
            var fn = $parse( attr.resetDirective );
            var masterModel = angular.copy( fn( scope ) );
    
            // Error check to see if expression returned a model
            if ( !fn.assign ) {
                throw Error( 'Expression is required to be a model: ' + attr.resetDirective );
            }
    
            element.bind( 'reset', function ( event ) {
                scope.$apply( function () {
                    fn.assign( scope, angular.copy( masterModel ) );
                    scope.form.$setPristine();
                });
    
                if ( event.preventDefault ) {
                    return event.preventDefault();
                }
                else {
                    return false;
                }
            });
        };
    }]);
    

    工作JS Fiddle

    【讨论】:

    • 我的按钮会是这个样子吗?:<button ng-click="resetForm()">Reset</button>
    • 但他还必须为每个字段定义默认值 $scope.myModel = { foo: '', bar: '' };
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 2016-12-08
    相关资源
    最近更新 更多