我正在使用 Rails 服务器(使用 Devise 进行身份验证)和 AngularJS 客户端。我已将 Rails 生成的表单添加到我的客户端页面,添加 ng-submit
Angular 指令,如下所示:
<%= form_for("user",
:url => user_session_path,
:html => { "ng-submit" => "doSignIn()" }) do |f| %>
这会生成一个具有 action
和 ng-submit
属性的表单,如下所示:
<form accept-charset="UTF-8" action="/users/sign_in" method="post" ng-submit="doSignIn()">
在封闭的 div
中的 Controller 定义中,我有一个 doSignIn
函数,目前它不执行任何操作:
$scope.doSignIn = function() {
console.log($scope.email, $scope.password);
};
$scope.email
和 $scope.password
使用 ng-model
绑定(bind)。或者,至少,它们应该是 - 我不能说,因为单击提交总是导致被定向到 /users/sign_in
。我的印象是使用 ng-submit
会阻止表单重定向用户。我也尝试过将 ng-click
添加到提交按钮,使用相同的方法,它也使用 doSignIn()
方法,我什至尝试过传递它事件并调用 event.preventDefault()
。似乎没有什么能阻止我被重定向。
我的最终目标是使用 AJAX 进行登录,但就目前而言,只要证明我可以停止自动重定向就很棒了!
最佳答案
I was under the impression that using ng-submit would prevent the form from redirecting the user.
如果 <form>
这只是一个正确的假设没有 action
与之关联的属性。当你使用 Rails form_for
助手,它生成一个 action
当您指定 url
时为您服务属性。
要防止提交表单,您必须遵循上述 Abraham P 的建议,并且 return false;
您不希望提交表单的地方。
关于ruby-on-rails - AngularJS ng-submit 在 Rails 生成的表单上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14216724/