1

我正在使用Codeigniter 3.1.8AngularJS v1.7.8开发博客应用程序

发表评论表单是通过 AngularJS 提交的。这是表格:

<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>

这是管理提交到 Codeigniter 后端的AngularJS 控制器:

 // 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);
        };
    });
}])

我还没有找到一种方法来清空表单并在它包含的数据被发送之后(并且仅在之后)它是原始的。

4

3 回答 3

1

像这样的东西:

$scope.createComment = function(){
  $http.post('api/comments/create/' + post_id, $scope.newComment)
    .then(() => {
       $scope.newComment = {
         slug: $routeParams.slug,
         post_id: '',
         name: '',
         email: '',
         comment: ''
      };
  });
};
于 2019-11-01T23:30:54.860 回答
1

还将表单设置为未触及: $scope.commentForm.$setUntouched()

于 2019-11-02T00:20:01.623 回答
1

它是这样工作的:

$scope.createComment = function() {
    $http.post('api/comments/create/' + post_id, $scope.newComment)
        .then(() => {
            $scope.newComment = {};
            $scope.commentForm.$setPristine();
            $scope.commentForm.$setUntouched();
        });
};
于 2019-11-02T00:30:49.967 回答