简体   繁体   中英

Passing variables to JS from controller Rails 4

I want to pass variables from controller to js file. Here what i do:

 #index.html.erb <%= content_tag 'div', id: 'coords', data: { coords: @coords} do %> <% end %> #@coords is defined in maps#index #@coords = Map.all 

In browser console i could easily call:

 $('#coords').data('coords') # or to acces 1st object $('#coords').data('coords')[0] # or to acces its 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"…} 
But i can not do the same in my Javascript. I get undefined on all of this calls. But if I inspect my code I can locate my div with data-coords: How to make my @coords be accessible in js?

if you js file is located like so: app/assets/javascripts/your-js.js.erb

then you can use your variables like so:

<%= @coords %>

EDIT:

my previous answer was wrong sing the js are precompiled. so my new answer is : create an 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 you can access that variable from the js:

globalPageScope.coords

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM