[英]Angular JS does not allow preventDefault or return false to work on form submission
我有一個表格,我想通過AJAX提供:
<form class="form-inline ng-pristine" ng-submit="sendForm()" method="post" action="/sign_up" accept-charset="UTF-8">
$scope.sendForm = (e) ->
e.preventDefault ->
console.log 'sendForm()'
return false
出現console.log
,並立即傳遞表單。
它忽略了e.preventDefault()
和return false
。
AngularJS讓我想起了蜜獾。 它只是不在乎。
我知道我參加派對的時間已經很晚了,但是如果你還沒弄清楚,你可以保留動作,並確保通過將$event
傳遞給ng-submit
函數來實際提交表單。 然后你可以使用event.preventDefault();
在完成所有處理后,在控制器中。
所以在你的情況下它將是:
<form class="form-inline ng-pristine" ng-submit="sendForm($event)" method="post" action="/sign_up" accept-charset="UTF-8">
$scope.sendForm = (e) ->
// doing stuff
e.preventDefault()
希望這可以幫助。
好吧,你不是“Angular方式”。 Angular提供了一個名為ng-submit的指令,它可以為您阻止默認(只要您沒有在表單上指定action屬性) 。
標記(通過驗證!)
<form name="myForm" ng-submit="sendForm()">
<div>
<input type="text" name="name" ng-model="data.name" required/>
<span ng-show="myForm.name.$error.required && myForm.name.$dirty">required</span>
</div>
<div>
<input type="email" name="email" ng-model="data.email" required/>
<span ng-show="myForm.name.$error.required && myForm.name.$dirty">required</span>
<span ng-show="myForm.name.$error.email && myForm.name.$dirty">invalid email</span>
</div>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
碼
app.controller("MyCtrl", function($scope, $http) {
$scope.sendForm = function (){
$http.post('/Submit/To/Url', $scope.data).success(function(data) {
alert('done!');
});
};
});
您可以通過將$event
傳遞到ng-click或ng-submit來獲取事件。 這就像依賴注入一樣,除了你的表達式。
HTML
<form class="form-inline ng-pristine" ng-submit="sendForm($event)" method="post" action="/sign_up" accept-charset="UTF-8">
CoffeeScript的
$scope.sendForm = (e) ->
e.preventDefault()
console.log 'sendForm()'
false
這是所有其他答案的更好解決方案。
假設您有表單元素附加的html5驗證必需屬性。
現在
<button ng-submit="Save($event)">SEND ME</button>
現在你運作了
$scope.Save = function($event){
$event.preventDefault();
.
. // may be an ajax request
.
return false;
}
這不僅會觸發html5驗證,還會阻止表單提交重定向。
解決這個問題的其他方法是使用指令。
app.directive("submit", [function () {
return {
scope: {
submit: "="
},
link: function (scope, element, attributes) {
element.bind("submit", function (loadEvent) {
return scope.submit(loadEvent);
});
}
}
}]);
<form submit="sendForm" method="post" action="/sign_up">
$scope.sendForm = function(e) {
if ($scope.whatever)
return true;
else
return false;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.