Clicking a button in the form causes the page to refresh
P粉231079976
P粉231079976 2024-01-16 10:54:04
0
2
480

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粉231079976
P粉231079976

reply all(2)
P粉489081732

You can try blocking the default handler:

html:

js:

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

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template