LoginSignup
7

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-09-22

例えば記事へのコメント投稿後に、そのフォームを再利用する際に、データを初期化しただけだとエラー表示が出てしまう。
ので、\$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.

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7