![](/img/trans.png)
[英]How can I dynamically populate morris.js charts from results sent via my controller?
[英]How to set morris.js values from Rails controller
我在体育应用程序中添加圆形图感到困难。 是否可以从控制器将morris.js值设置为变量? 我在控制器中有@diet_calories变量,我想以60%-> 20%-> 20%的关系显示Carbs-> Protein- > Fat。 如果我在脚本标签中设置carbs的值( 值:@diet_calories * 0.6 ),则它不起作用。 您是否有解决建议?
application.html.erb:
<script>
new Morris.Donut({
element: 'diet-circle',
data: [
{ label: "Carbs", value: @diet_calories * 0.6 },
{ label: "Protein", value: @diet_calories * 0.2 },
{ label: "Fat", value: @diet_calories * 0.2 }
]
});
</script>
info_controller.rb:
def diet
if current_user.activity == "Sedentary"
if current_user.goals == "Lose Weight"
@diet_calories = ((@bmr * 1.1) - 300).to_i
elsif current_user.goals == "Maintain Weight"
@diet_calories = (@bmr * 1.1).to_i
elsif current_user.goals == "Add some weight"
@diet_calories = ((@bmr * 1.1) + 300).to_i
end
elsif current_user.activity == "Low"
if current_user.goals == "Lose Weight"
@diet_calories = ((@bmr * 1.5) - 300).to_i
elsif current_user.goals == "Maintain Weight"
@diet_calories = (@bmr * 1.5).to_i
elsif current_user.goals == "Add some weight"
@diet_calories = ((@bmr * 1.5) + 300).to_i
end
elsif current_user.activity == "Medium"
if current_user.goals == "Lose Weight"
@diet_calories = ((@bmr * 1.7) - 300).to_i
elsif current_user.goals == "Maintain Weight"
@diet_calories = (@bmr * 1.7).to_i
elsif current_user.goals == "Add some weight"
@diet_calories = ((@bmr * 1.7) + 300).to_i
end
elsif current_user.activity == "High"
if current_user.goals == "Lose Weight"
@diet_calories = ((@bmr * 2.1) - 300).to_i
elsif current_user.goals == "Maintain Weight"
@diet_calories = (@bmr * 2.1).to_i
elsif current_user.goals == "Add some weight"
@diet_calories = ((@bmr * 2.1) + 300).to_i
end
end
Diet.html.erb:
<div id="diet-circle"></div>
您可以通过在application.html.erb中进行此更改来实现
<script>
var diet_calories = <%= @diet_calories %>
new Morris.Donut({
element: 'diet-circle',
data: [
{ label: "Carbs", value: diet_calories * 0.6 },
{ label: "Protein", value: diet_calories * 0.2 },
{ label: "Fat", value: diet_calories * 0.2 }
]
});
</script>
为了进一步了解变量从Rails到javascript的传递,请看一下这个railscast。
尝试:
<script>
new Morris.Donut({
element: 'diet-circle',
data: [
{ label: "Carbs", value: <%= @diet_calories %> * 0.6 },
{ label: "Protein", value: <%= @diet_calories %> * 0.2 },
{ label: "Fat", value: <%= @diet_calories %> * 0.2 }
]
});
</script>
.erb
代表Embedded RuBy 。 在.erb
文件中评估Ruby代码(例如,使用控制器中设置的实例变量),您需要使用<%= ruby code %>
您可以在此处阅读有关Erb模板的介绍
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.