AngularJS不正确的手柄按钮类型=“复位”?(AngularJS does not prope

2019-10-19 20:46发布

我有以下几点:

<form name="editor">
    <h2>Create/Update</h2>
    {{ editor.title.$error.required }}
    <div ng-class="{ 'has-error': editor.title.$invalid && editor.title.$dirty, 'has-success': editor.title.$valid }" class="form-group">
        <input type="text" name="title" ng-model="project.title" placeholder="title" required class="form-control">
        <span class="input-icon fui-check-inverted" ng-show="editor.title.$valid"></span>
    </div>
    {{ editor.description.$error.required }}
    <div ng-class="{ 'has-error': editor.description.$invalid && editor.description.$dirty, 'has-success': editor.description.$valid }" class="form-group">
        <textarea name="description" ng-model="project.description" placeholder="description" required class="form-control"></textarea>
        <span class="input-icon fui-check-inverted" ng-show="editor.description.$valid"></span>
    </div>
    <button ng-click="save()" type="submit" class="btn btn-primary btn-embossed">Save</button>
    <button type="reset" class="btn btn-inverse">Reset</button>
    <a href="#/">Back</a>
</form>

我遵循“JavaScript的项目”教程角网站主页 。 我已经添加了复位按钮detail.html。 问题是,它的行为。 当我清理我自己的字段,验证失败,但是当我点击复位按钮,字段被清理,但形式剩余的有效。 那是一个角度的错误? 而如何把它修好?

Answer 1:

我相信你要找的是什么$setPristine();

$setPristine();

设置形式到它的原始状态。

这个方法可以被调用以除去“NG-脏”类和形式设置为它的原始状态(NG-原始类)。 这种方法也将传播到包含在该表单中的所有控件。

设置一个形式返回到原始状态,当我们要在保存或将其复位后“重用”形式往往是有用的。

通过http://docs.angularjs.org/api/ng/type/form.FormController

例如JS

$scope.data = {
    "username": "", 
    "password" : ""
};

$scope.reset = function() {
  $scope.data.username = "";
  $scope.data.password = "";
  $scope.form.$setPristine();
};

例如标记

<form name="form" id="form" novalidate>
        <input name="username" ng-model="data.username" placeholder="Name" required/>
        <input name="password" ng-model="data.password" placeholder="Password" type="password" required/>
        <div>
            <hr />
            <button class="button" ng-click="">Login</button>
            <button class="button" ng-click="reset()">Reset</button>
        </div>
</form>

演示http://plnkr.co/edit/xTQLQH8mCCkY0tIX6n8Y?p=preview


更新:简化的解决方案

如果你想弄死控制器功能reset()您可以设置type="reset"最初完成的,但需要$setPristine()ng-click

<button class="button" type="reset" ng-click="form.$setPristine()">Reset</button>

新普拉克: http://plnkr.co/edit/tNKPyyMboAQjeURn6m6W?p=preview



文章来源: AngularJS does not proper handle button type=“reset”?