I used AngularJS on Rails form_for. The most annoying thing is form_for generates form tag with action attribute.
Environment
- Rails 4.1.8
- Ruby 2.2.2
- AngularJS 1.4.7
- Ubuntu 15.04
Circumstance
Rails form_for
generates form tag with some attributes, including action
. Of course, we can add other attributes. But, AngularJS conflicts with this.
In the following code, problem occurs.
1 2 3 4 5 |
<%=form_for(@user, html: {'data-ng-submit': 'mainCtrl.create()', novalidate: :novalidate, name: 'createForm'}) do |f|%> <%=f.label :name%> <%=f.text_field :name, required: :required, 'data-ng-model': 'user.name'%> <button>submit</button> <%end%> |
After clicking the button, AngularJS process will be executed and original form process will be executed.
AngularJS prevent original process when form doesn’t have action attribute, but rails add action attributes automatically. I couldn’t find the way to prevent rails from adding action attribute.
Solution
Add onsubmit="return false;"
to the form tag.
1 2 3 4 5 |
<%=form_for(@user, html: {'data-ng-submit': 'mainCtrl.create()', novalidate: :novalidate, name: 'createForm', onsubmit: "return false;"}) do |f|%> <%=f.label :name%> <%=f.text_field :name, required: :required, 'data-ng-model': 'user.name'%> <button>submit</button> <%end%> |
また AngularJS: How to prevent form submission after click on button? に記載されているような方法もありますが、 javascript として 他のところで使えないので、 上に書いたやり方の方がきれいに見えます。