[英]How can I empty this AngularJS form after submitting the data?
我正在使用Codeigniter 3.1.8和AngularJS 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 controller :
// 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);
};
});
}])
我還沒有找到一種方法來清空表單並在它包含的數據被發送之后(並且僅在之后)它是原始的。
像這樣的東西:
$scope.createComment = function(){
$http.post('api/comments/create/' + post_id, $scope.newComment)
.then(() => {
$scope.newComment = {
slug: $routeParams.slug,
post_id: '',
name: '',
email: '',
comment: ''
};
});
};
還將表單設置為untouched : $scope.commentForm.$setUntouched()
。
它是這樣工作的:
$scope.createComment = function() {
$http.post('api/comments/create/' + post_id, $scope.newComment)
.then(() => {
$scope.newComment = {};
$scope.commentForm.$setPristine();
$scope.commentForm.$setUntouched();
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.