我的表单有一个简单的表单验证功能,它由两个文本字段和两个下拉字段组成。如果我没有填写某个字段,它会提醒我,但它会从所有其他字段中删除信息,并仍然提交表单。我该如何解决这个问题?我知道这可能与我的表单提交按钮中的 ng-click 功能有关,但我无法找到解决方案。
(1) javascript 文件中的控制器
function initMap(data) {
var uluru = {lat: 29.643220, lng: -82.350427};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: uluru
});
// Marker Images
var image = 'https://image.ibb.co/nmGCo5/Spot3.png';
var image3 = 'http://www.poolcleaningfl.com/wp-content/uploads/2014/11/map_icon.png';
placeMarker(data, map);
}
function mainController($scope, $http) {
$scope.formData = {};
$http.get('/api/events')
.success(function(data) {
$scope.events = data;
initMap(data);
for(i = 0; i < data.length; i++) {
console.log(data[i].eventLocation);
}
})
.error(function(data) {
console.log('Error: ' + data);
});
// when submitting the add form, send the text to the node API
$scope.createEvent = function() {
$http.post('/api/events', $scope.formData)
.success(function(data) {
$scope.formData = {}; // clear the form so our user is ready to enter another
$scope.events = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
// if a field is left empty, sent alert, return false
$scope.validateForm = function() {
if (!$scope.formData.eventName) {
alert("Please give your event a name!");
return false;
}
else if (!$scope.formData.eventType) {
alert("Please choose an event type!");
return false;
}
else if (!$scope.formData.eventLocation) {
alert("Please choose a location!");
return false;
}
else if (!$scope.formData.eventDetails) {
alert("Please include some details about your event!");
return false;
}
return true;
}
}
(2) html文件中的表格
<!-- Event form -->
<div class="col-md-6">
<form name="myFor" ng-submit="validateForm()">
<!-- Event name -->
<div class="form-group">
<label class="styleone">Event Name</label>
<input type="text" class="form-control" ng-model="formData.eventName" placeholder="Event name">
</div>
<!-- Event type -->
<div class="form-group">
<label class="styleone">Type</label>
<select class="form-control selectpicker" ng-model="formData.eventType">
<option>Type 1</option>
<option>Type 2</option>
<option>Type 3</option>
</select>
</div>
<!-- Event location -->
<div class="form-group">
<label class="styleone">Location</label>
<select class="form-control selectpicker" data-live-search="true" ng-model="formData.eventLocation">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</div>
<!-- Event details -->
<div class="form-group">
<label class="styleone">Event Details</label>
<textarea class="form-control" ng-model="formData.eventDetails" rows="2" placeholder="Add details about your event"></textarea>
</div>
<div class="text-center">
<button class="btn btn-info" ng-click="createEvent()">Submit</button>
</div>
</form>