我对以下有关 angularJS 表单验证的代码感到困惑。请参阅下面的 HTML 表单和 JavaScript 代码,这是我们的讲师给出的示例代码。我不明白的是这个标签
<div class="form-group" ng-class="{ 'has-error': feedbackForm.firstName.$error.required && !feedbackForm.firstName.$pristine }">
在 ng-class ="{...}"中,“feedbackForm”是表单的名称,但“firstName”是 $scope.feedback 对象的属性,如 JavaScript 中所述代码。什么机制将它们连接在一起以便可以通过“feedbackFrom.firstName”访问?
此外,“feedbackForm.firstName”后面的“$error”和“$pristine”是什么?它是 AngularJS 预定义的对象吗?再说一次,如何使用句点来访问它们?
HTML 表单:
<div ng-controller="FeedbackController">
<form role="form" name="feedbackForm" ng-submit="sendFeedback()" novalidate>
<div class="form-group" ng-class="{ 'has-error': feedbackForm.firstName.$error.required &&!feedbackForm.firstName.$pristine }">
<label for="firstname" class="col-sm-2 control-label">First Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="firstname" name="firstname" placeholder="Enter First Name" ng model="feedback.firstName" required>
<span ng-show="feedbackForm.firstName.$error.required && !feedbackForm.firstName.$pristine" class="help-block">Your first name is required.</span>
</div>
</div>
</form>
相关JavaScript代码:
.controller('ContactController', ['$scope', function($scope) {
$scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" };
var channels = [{value:"tel", label:"Tel."}, {value:"Email",label:"Email"}];
$scope.channels = channels;
$scope.invalidChannelSelection = false;
}])
.controller('FeedbackController', ['$scope', function($scope) {
$scope.sendFeedback = function() {
console.log($scope.feedback);
if ($scope.feedback.agree && ($scope.feedback.mychannel == "")) {
$scope.invalidChannelSelection = true;
console.log('incorrect');
}
else {
$scope.invalidChannelSelection = false;
$scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" };
$scope.feedback.mychannel="";
$scope.feedbackForm.$setPristine();
console.log($scope.feedback);
}
};
}])
最佳答案
你有点不对劲。
feedbackForm.firstName
引用表单 feedbackForm
和输入字段 firstName
。
$scope.feedback
对象由 ngModel 引用并处理模型绑定(bind)。
$error
和 $pristine
是 AngularJS 添加的类,用于指示输入字段的状态。
关于javascript - AngularJS 表单验证中的 ng-class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34212194/