我對以下關於angularJS表單驗證的代碼感到困惑。請參閱下面的HTML表單和JavaScript代碼,它是示例代碼,作爲我們的教師。我不明白的是在此標記ng-class在AngularJS表單驗證中
<div class="form-group" ng-class="{ 'has-error': feedbackForm.firstName.$error.required && !feedbackForm.firstName.$pristine }">
納克級的內部=「{...}」中,「feedbackForm」是形式的名稱,但「名字」是一個屬性在$ 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);
}
};
}])
謝謝,這有幫助! –