javascript - Passing variables to JS from controller Rails 4 -
i want pass variables controller js file. here do:
#index.html.erb <%= content_tag 'div', id: 'coords', data: { coords: @coords} %> <% end %> #@coords defined in maps#index #@coords = map.all
in browser console call:
$('#coords').data('coords') # or acces 1st object $('#coords').data('coords')[0] # or acces attribute $('#coords').data('coords')[0].lat #object {id: 1, vibration_level: 456, lat: "71.45543", lon: "53.43424", time_sent: "1994-05-20t00:00:00.000z"…}
if js file located so: app/assets/javascripts/your-js.js.erb
then can use variables so:
<%= @coords %>
edit:
my previous answer wrong sing js precompiled. new answer : create html app/views/layouts/_page_scope.html.erb
<% globalpagescope = {} globalpagescope['coords'] = @coords if @coords %> <script type="text/javascript"> document.globalpagescope = <%= raw globalpagescope.to_json %>; </script>
then can access variable js:
globalpagescope.coords
Comments
Post a Comment