search

Home  >  Q&A  >  body text

Clicking the button will cause the form to refresh.

<p>I have a form in Angular with two button labels. A button submits the form on <code>ng-click</code>. The other button is purely for navigation using <code>ng-click</code>. However, when this second button is clicked, AngularJS causes the page to refresh, triggering a 404 error. I set a breakpoint in the function and it triggers my function. If I do any of the following, it stops: </p> <ol> <li>If I remove <code>ng-click</code>, the button does not cause the page to refresh. </li> <li>If I comment out the code in the function, it does not cause the page to refresh. </li> <li>If I change the button label to an anchor label (<code><a></code>) and add <code>href=""</code> it does not cause a refresh . </li> </ol> <p>The latter seems to be the easiest solution, but why does AngularJS run any code after my function that causes the page to reload? Looks like a bug. </p> <p>This is the form: </p> <pre class="brush:php;toolbar:false;"><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></pre> <p>This is the controller method: </p> <pre class="brush:php;toolbar:false;">$scope.showChangePassword = function() { $scope.selectedLink = "changePassword"; };</pre> <p><br /></p>
P粉523625080P粉523625080466 days ago466

reply all(2)I'll reply

  • P粉637866931

    P粉6378669312023-08-15 11:55:54

    You can try blocking the default handler:

    html:

    <button ng-click="saveUser($event)">

    js:

    $scope.saveUser = function (event) {
      event.preventDefault();
      // 你的代码
    }

    reply
    0
  • P粉821274260

    P粉8212742602023-08-15 11:39:51

    If you look at the W3C spec, it seems like the obvious thing to try is to mark type='button' on the button element that you don't want submitted.

    Special attention should be paid to the location it says

    reply
    0
  • Cancelreply