简体   繁体   中英

Button unexpectedly submitting form

So, I'm building a form where you select a date, then you can add timeslots to that date to schedule things. Something like this:

<form name="NewForm" ng-submit="submitForm(NewForm)">
    <form-group>
       <angular-ui datepicker>
       <button ng-click="addRow()">
    </form-group>
    <form-group ng-repeat="timepicker in timepickers track by $index">
        <angular-ui timepicker>
        <select box for tasks to pick from>
        <button class="btn btn-danger" ng-click="deleteRow($index)">
    </form-group>
    <button type="submit" class="btn btn-primary">
</form>

Then in the controller I have:

$scope.timepickers = []

$scope.addRow = function() {
    $scope.timepickers.push({ some default object data to fill out the row });
}

$scope.deleteRow = function(index) {
    $scope.timepickers.splice(index, 1);
}

$scope.submitForm(form) {
     if ($scope.timepickers.length < 1) {
         //do some stuff and don't send the form  
     } 
     else if (form.$valid) {
         //send form data to api
     }
     else {
         //do some other stuff and don't send the form
     }
}

The delete button was the last thing I added, and everything was working fine before I added it. The problem, however, is that sometimes when I push the delete button on a row, it submits the form and for the life of me I can't figure out why.

If I only have 1 or 2 'rows' it works fine. The delete button deletes the row and I can keep adding new rows, etc. If I have more than 2 rows added, though, AND I try to delete one of the rows in the middle (ie where if I checked if '$middle == true' in the ng-repeat), then it deletes the row and calls the submitForm function.

I know it actually runs through the submitForm function because if I don't fill out the form completely, then the validation stuff still triggers and the submit doesn't go through.

Anyone have any ideas?

您需要添加按钮类型的属性:

<button class="btn btn-danger" ng-click="deleteRow($index)" type="button">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM