在我的角度控制器中,我尝试验证用户是否插入了 5 个字符,如果少于 5 个字符,则应显示警告。我的控制器:
var app = angular.module('myapp', ['ui.bootstrap']);
app.controller('FeedController', function ($scope, $http) {
$scope.customPostText = "";
$scope.sendMessage = function()
{
console.log("text ");
console.log($scope.customPostText);
var length = $scope.customPostText.length
//could us:
//if ($scope.postcommentForm.customPostText.$valid) instead to check if valid
//but I want to see the length.
if(length >4 && length < 255)
{
alert("not undefined");
}
else
{
alert("message needs 5 characters you have."+length);
}
}
});
出于某种原因,如果我键入的字符少于 5 个,$scope.customPostText 将变为未定义并在日志中写入错误:
无法读取未定义的属性“长度”
但是在 5 个或更多字符上没有问题,我发现这是因为我在 html 中使用了 ng-minlength:
<div ng-controller="FeedController">
<div class="row">
<form id="postcommentForm" name="postcommentForm">
<div class="form-group">
<div class="input-group" id="post-comment-textarea">
<textarea class="form-control" name="customPostText" id="customPostText" maxlength="255"
ng-model="customPostText"
ng-minlength="5"
ng-maxlength="255"
ng-trim="true"
ng-class="{ 'success-border': postcommentForm.customPostText.$valid ,'error-border': !postcommentForm.customPostText.$valid }"
ng-required="true"
></textarea>
<span class="input-group-addon btn btn-success"
ng-disabled="{{postcommentForm.customPostText.$valid == false}}"
ng-click="sendMessage()"
ng-class="{ 'success-border': postcommentForm.customPostText.$valid ,'error-border': !postcommentForm.customPostText.$valid }" >
Send
</span>
</div>
</div>
</form>
</div>
</div>
但是,我需要 ng-minlength 用于在 ng-class 中使用的验证:
ng-class="{ 'success-border': postcommentForm.customPostText.$valid ,'error-border': !postcommentForm.customPostText.$valid }"
如何使用 ng-minlength 而不会出现值未定义的问题?