我有一個Rails 3.2.8應用程序,我在窗體中動態地應用一些AngularJS進行計算。Rails AngularJS計算嵌套窗體
我有一個基本的測試應用程序,它將投資者映射到多個房屋,並且每個房屋都有一個成本和價值,我希望在最後完成。
這裏是我的形式
<div ng-controller="InvestorCtrl">
<%= form_for(@investor) do |f| %>
<% if @investor.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@investor.errors.count, "error") %> prohibited this investor from being saved:</h2>
<ul>
<% @investor.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<% i = 0 %>
<%= f.fields_for :houses do |builder| %>
<%= builder.label :address %>
<%= builder.text_field :address %>
<%= builder.label :suburb %>
<%= builder.text_field :suburb %>
<%= builder.label :cost %>
<%= builder.text_field :cost, "ng-model" => "timesheets[#{i}].cost", "ng-change" => "calc_cost()" %>
<%= builder.label :value %>
<%= builder.text_field :value, "ng-model" => "timesheets[#{i}].value" %>
<% i = i + 1 %>
<% end %>
<div class="field">
<%= f.label :total_cost %>
<%= f.number_field :total_cost, "ng-model" => "total_cost" %>
</div>
<div class="field">
<%= f.label :total_value %>
<%= f.number_field :total_value, "ng-model" => "total_value" %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
</div>
這裏是angularjs的CoffeeScript我使用
$ (event) ->
app = angular.module "investor", []
app.controller("InvestorCtrl", ["$scope", ($scope) ->
$scope.timesheets = [
{ cost: 295000, value: 450000 },
{ cost: 600000, value: 620000 },
{ cost: 1000000, value: 900000 },
]
$scope.calc_cost = ->
total = 0
for ts in $scope.timesheets
total = total + ts.cost
$scope.total_cost = total
$scope.calc_cost()
])
angular.bootstrap document, ['investor']
當我打開一個新的形式,我建的三間房子在控制器中,像這樣:
def new
@investor = Investor.new
3.times { @investor.houses.build }
respond_to do |format|
format.html # new.html.erb
format.json { render json: @investor }
end
end
轉到新窗體時總成本計算正確,但是當我更改任何t他設置'成本'值'total_cost'字段設置爲空白。
我是否正確綁定? 有沒有更簡單的方法來綁定使用AngularJS與Rails模板的嵌套窗體?
目前我只是試圖使用AngularJS將房屋「成本」價值總和計入'total_cost'字段。
的fields_for是創造獨特的NG-型號名稱問題當我在房屋'成本'字段中輸入一個新值時,它會中斷計算並將total_cost設置爲空白。 – map7