[英]Angular ng-submit called twice
我有一個角度表單,其提交方法被擊中兩次,我不知道為什么。 我對 Angular 很陌生,所以我可能忽略了一些相當簡單的東西......
html:
<div ng-app="RegistrationApp" ng-controller="RegistrationController">
<form name="accountForm" ng-submit="submitAccount($event, accountForm, account)" novalidate>
// inputs here...
<button type="submit" class="btn btn-success pull-right" ng-disabled="accountForm.$invalid">Submit</button>
</form>
</div>
JS:
var RegistrationApp = angular.module('RegistrationApp', []);
RegistrationApp.controller('RegistrationController', function ($scope) {
$scope.submitAccount = function (evt, form, account) {
console.log('submitAccount() hit');
console.log(evt);
console.log(form);
evt.stopPropagation();
// AJAX code
});
});
控制台窗口:
submitAccount() hit
o.Event {originalEvent: Event, type: "submit", isDefaultPrevented: function, timeStamp: 1394139847226, jQuery210012237170152366161: true…}
c {$error: Object, $name: "accountForm", $dirty: true, $pristine: false, $valid: true…}
submitAccount() hit
o.Event {originalEvent: Event, type: "submit", isDefaultPrevented: function, timeStamp: 1394139847226, jQuery210012237170152366161: true…}
Constructor {$error: Object, $name: "accountForm", $dirty: true, $pristine: false, $valid: true…}
所以,我嘗試的第一件事是停止傳播事件,但這並沒有任何實際效果。 經過事件對象后,它們看起來是相同的。 唯一不同的是“表單”對象。 屬性相同,只是一個顯示“c”,另一個顯示“Constructor”。
任何想法可能導致此觸發兩次? 在這兩種情況下,事件目標都設置為表單元素,並且我沒有使用任何onclick
函數或表單中的任何其他類型的事件。
發生這種情況的另一個原因(剛剛發生在我身上):
我有以下幾點:
<form ng-submit="myCtrl.search()">
<button type="submit">Search</button>
<button type="submit" class="mobile-only" ng-click="myCtrl.search()">Go</button>
</form>
我在表單中有另一個按鈕,它綁定到與ng-click
上的ng-submit
相同的功能,這導致該方法被調用兩次。
檢查你沒有兩次聲明你的控制器:一個在 HTML 中,正如我在上面看到的,另一個在配置你的路由時。 如果是這種情況,控制器被實例化兩次,因此監聽器被調用兩次
一個原因發生在我身上,我不確定這是否會發生在其他任何人身上:)
在我的控制器中,我有:
$scope.submit = function() { someThingHere };
在視圖中
<form ng-submit="submit()">
</form>
這樣,該表單已經“神秘地”提交了兩次,以解決我不得不將$scope.submit
重命名$scope.submit
其他名稱的問題。
這種行為有多種原因(其中一些已經指出):
仔細檢查它們,因為在某些情況下很容易通過它們
就我而言,它是“ng-app”指令,當我手動引導所有內容時,我並不依賴它。
我在 Angular 12 中使用響應式表單遇到了這種情況,因為我在表單聲明中有一個不必要的
ngForm<\/code>屬性:
<form ngForm [formGroup]="formGroup" (ngSubmit)="onSubmit()">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.