单击表单中的按钮会导致页面刷新 [英] Clicking a button within a form causes page refresh
问题描述
我在Angular中有一个表单,里面有两个按钮标签。一个按钮在 ng-click
上提交表单。另一个按钮纯粹用于使用 ng-click
进行导航。但是,当单击第二个按钮时,AngularJS会导致页面刷新,触发404.我在函数中删除了一个断点,它正在触发我的函数。如果我执行以下任何操作,它将停止:
I have a form in Angular that has two buttons tags in it. One button submits the form on ng-click
. The other button is purely for navigation using ng-click
. However, when this second button is clicked, AngularJS is causing a page refresh which triggers a 404. I’ve dropped a breakpoint in the function and it is triggering my function. If I do any of the following, it stops:
- 如果我删除
ng-click
,该按钮不会导致页面刷新。 - 如果我注释掉函数中的代码,它不会导致页面刷新。
- 如果我使用
href =将按钮标记更改为锚标记(
,然后它不会导致刷新。< a>
)
- If I remove the
ng-click
, the button doesn’t cause a page refresh. - If I comment out the code in the function, it doesn’t cause a page refresh.
- If I change the button tag to an anchor tag (
<a>
) withhref=""
, then it doesn’t cause a refresh.
后者似乎是最简单的解决方法,但是为什么AngularJS甚至在我的函数之后运行任何代码导致页面重新加载?好像是一个错误。
The latter seems like the simplest workaround, but why is AngularJS even running any code after my function that causes the page to reload? Seems like a bug.
以下是表格:
<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>
以下是控制器方法:
$scope.showChangePassword = function() {
$scope.selectedLink = "changePassword";
};
推荐答案
如果你看一下 W3C规范,看起来很明显的尝试是用<$标记你的按钮元素c $ c> type ='button'当你不想让他们提交时。
If you have a look at the W3C specification, it would seem like the obvious thing to try is to mark your button elements with type='button'
when you don't want them to submit.
特别需要注意的是它在哪里说
The thing to note in particular is where it says
没有指定type属性的按钮元素表示与type属性设置为submit的按钮元素相同的东西
A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"
这篇关于单击表单中的按钮会导致页面刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!