angularjsng-submit

How can I empty this AngularJS form after submitting the data?


I am working on a blog application with Codeigniter 3.1.8 and AngularJS v1.7.8.

The post comments form is submitted via AngularJS. Here is the form:

<form name="commentForm" novalidate>
    <div class="row uniform">
        <div class="form-controll 6u 12u$(xsmall)">
            <input type="text" name="name" id="name" ng-model="newComment.name" placeholder="Name" ng-required="true" />
            <span class="error" ng-show="(commentForm.name.$touched && commentForm.name.$invalid) || (commentForm.$submitted && commentForm.name.$invalid)">This field can not be empty</span>
        </div>
        <div class="form-controll 6u$ 12u$(xsmall)">
            <input type="email" name="email" id="email" ng-model="newComment.email" placeholder="Email" ng-required="true" />
            <span class="error" ng-show="(commentForm.email.$touched && commentForm.email.$invalid) || (commentForm.$submitted && commentForm.email.$invalid)">Enter a valid email address</span>
        </div>
        <div class="form-controll 12u$">
            <textarea name="comment" rows="6" id="message" ng-model="newComment.comment" placeholder="Comment" ng-required="true"></textarea>
            <span class="error" ng-show="(commentForm.comment.$touched && commentForm.comment.$invalid) || (commentForm.$submitted && commentForm.comment.$invalid)">This field can not be empty</span>
        </div>
        <!-- Break -->
        <div class="12u$">
            <input type="submit" value="Add comment" ng-click="createComment()" class="button special fit" />
        </div>
    </div>
</form>

Here is the AngularJS controller that manages it's submission to the Codeigniter back-end:

 // Post comment
.controller('PostCommentController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
    const slug = $routeParams.slug;
    $http.get('api/' + slug).then(function(response) {

        let post_id = response.data.post.id

        $scope.newComment = {
            slug: $routeParams.slug,
            post_id: post_id,
            name: $scope.name,
            email: $scope.email,
            comment: $scope.comment
        };

        $scope.createComment = function(){
          $http.post('api/comments/create/' + post_id, $scope.newComment);
        };
    });
}])

I have not yet been able to find a way to empty the form and make it pristine after (and only after) the data it contains has been sent.


Solution

  • Also set the form as untouched: $scope.commentForm.$setUntouched().