Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

AngularJSのフォームを、投稿後に再利用する際、手付かずの状態に戻したい

More than 5 years have passed since last update.

例えば記事へのコメント投稿後に、そのフォームを再利用する際に、データを初期化しただけだとエラー表示が出てしまう。
ので、\$dirtyがfalse(\$pristineがtrue)の状態に戻したい。

いわゆるブログのコメント投稿とかのよくあるやつ.

form.FormControllerの$setPristine()を使う。

comment_new.html
  <div ng-controller="CommentNewCtrl">
    <form name="commentNewForm">
      <div class="form-group"
           ng-class="{'has-error': commentNewForm.content.$dirty && commentNewForm.content.$invalid }">
        <textarea class="form-control" ng-model="comment.content" placeholder="" tabindex="1" name="content"
                  required></textarea>
        <span ng-show="commentNewForm.content.$dirty&&commentNewForm.content.$error.required">
          必須です
        </span>
      </div>
      <button ng-disabled="!commentNewForm.$valid" ng-click="save()">コメントを投稿</button>
    </form>
  </div>

comment_new.coffee
angular.module('myApp')
.controller 'CommentNewCtrl', ($scope, Comment) ->

# .........................

  $scope.save = ->
    $scope.comment.$create((data)->
      # .........................
      $scope.comment = new Comment(report_id: reportId) #<- 初期化
      $scope.commentNewForm.$setPristine()  # <- コレ
    )

OK.

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away