我有一个问题,我想制作计数器来计算textarea中的字符,它会限制你应该添加多少个字符,即添加固定长度的注释。我使用了ng-model="seeMore.comment" in
textarea and I would like to dynamically show the length of the textarea, so I am using
.controller('seeMoreCtrl', function($scope, User, $location, $window, $timeout){
var app = this;
app.AddComment = function(comment, valid) {
app.disabled = true;
app.loading = true;
app.errorMsg = false;
if(valid){
var userComment = {};
userComment._id = app.currentProduct;
userComment.comment = app.comment;
User.postComment(userComment).then(function(data){
if(data.data.success){
app.successMsg = 'Dzękujemy za Twoją opinię!';
app.loading = false;
$timeout(function(){
$scope.seeMore.comment = '';
app.AddCommentForm.$setPristine();
app.AddCommentForm.$setUntouched();
app.successMsg = false;
},2000)
} else {
app.disabled = false;
app.loading = false;
app.errorMsg = data.data.message;
}
});
} else {
app.disabled = false;
app.loading = false;
app.errorMsg = 'Twoja opinia nie została dodana. Musisz dodać jakąś treść.';
$timeout(function(){
app.AddCommentForm.$setPristine();
app.AddCommentForm.$setUntouched();
app.errorMsg = false;
},3000)
}
}
})
<form name="seeMore.AddCommentForm" ng-submit="seeMore.AddComment(comment, seeMore.AddCommentForm.$valid)" novalidate>
<div ng-class="{'has-success':(seeMore.AddCommentForm.comment.$valid && !seeMore.AddCommentForm.comment.$pristine), 'has-error':(!seeMore.AddCommentForm.comment.$valid && !seeMore.AddCommentForm.comment.$pristine) || (!seeMore.AddCommentForm.comment.$valid && seeMore.AddCommentForm.$submitted)}">
<textarea class="form-control" id="text-area-comment" name="comment" ng-model="seeMore.comment" ng-minLength="10" required></textarea>
<ul ng-show="(!seeMore.AddCommentForm.comment.$pristine && seeMore.AddCommentForm.comment.$error.minlength)" class="help-block comment-conditions">
<li>{{ 10 - seeMore.comment.length}}</li>
</ul>
<button class="btn btn-warning button-comment-user">Add comment</button>
</div>
</form>
答案 0 :(得分:3)
由于您使用验证器(`ng-minlength =“10”),因此除非输入有效,否则不会更新您在ng-model中使用的模型。因此,除非您在textarea中添加超过10个字符,否则seeMore.comment将没有值。
在自定义指令段落here中删除:
$ validators对象中的每个函数都接收modelValue和 viewValue作为参数。然后AngularJS将调用$ setValidity 内部使用函数的返回值(true:valid,false: 无效)。每次输入时都会执行验证功能 更改(调用$ setViewValue)或绑定模型更改时。 验证在成功运行$ parsers之后发生 $格式化程序,分别。失败的验证器按密钥存储 ngModelController。$错误。
您的解决方案是根据此输入直接使用$ viewValue&amp; minlength validato。由于您可以通过seeMore.AddCommentForm
(表单的名称attr)访问表单对象,因此只需使用seeMore.AddCommentForm.$error.minlength[0].$viewValue.length
<ul ng-show="(!seeMore.AddCommentForm.comment.$pristine && seeMore.AddCommentForm.comment.$error.minlength)" class="help-block comment-conditions">
<li>{{ 10 - seeMore.AddCommentForm.$error.minlength[0].$viewValue.length}}</li>
</ul>