search

Home  >  Q&A  >  body text

Clicking a button in the form causes the page to refresh

I have an Angular form with two button labels. Submit the form on ng with one click - click. The other button is purely for navigation using ng-click. However, when the second button is clicked, AngularJS causes the page to refresh, triggering a 404. I have placed a breakpoint in the function and it is triggering my function. If I do any of the following it stops:

  1. If I remove ng-click, the button does not cause the page to refresh.
  2. If I comment out the code in the function, it does not cause the page to refresh.
  3. If I change the button tag to an anchor tag (<a>) using href="", it does not cause a refresh.

The latter seems to be the simplest solution, but why does AngularJS even run any code after my function that causes the page to reload? Looks like a bug.

The table is as follows:

<form class="form-horizontal" name="myProfile" ng-switch-when="profile">
  <fieldset>
    <div class="control-group">
      <label class="control-label" for="passwordButton">Password</label>
      <div class="controls">
        <button id="passwordButton" class="secondaryButton" ng-click="showChangePassword()">Change</button>
      </div>
    </div>

    <div class="buttonBar">
      <button id="saveProfileButton" class="primaryButton" ng-click="saveUser()">Save</button>
    </div>
  </fieldset>
</form>

This is the controller method:

$scope.showChangePassword = function() {
  $scope.selectedLink = "changePassword";
};

P粉231079976P粉231079976347 days ago517

reply all(2)I'll reply

  • P粉489081732

    P粉4890817322024-01-17 10:01:09

    You can try blocking the default handler:

    html:

    js:

    $scope.saveUser = function (event) {
      event.preventDefault();
      // your code
    }

    reply
    0
  • P粉596191963

    P粉5961919632024-01-17 00:42:50

    If you look at the W3C spec, it looks like apparently you can try tagging the button element with type='button' when you don't want it to submit.

    Special attention should be paid to where it says

    reply
    0
  • Cancelreply