[ASP.net MVC 4] 使用AngularJS計算Html Table中的小計數量
最近案子有用到
代碼:
HomeController.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationAngularHtmlTable.Controllers
{
public class Product
{
public int id { get; set; }
public string ProductName { get; set; }
public int Num { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
//假裝從DB撈出的資料
List<Product> orders = new List<Product>()
{
new Product(){ id=1, ProductName="商品一號", Num=10},
new Product(){ id=2, ProductName="商品二號", Num=20},
new Product(){ id=3, ProductName="商品三號", Num=30},
};
//轉成Json字串
ViewData["orders"] = JsonConvert.SerializeObject(orders);
return View();
}
}
}
Index.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html ng-app>
<head>
<meta name="viewport" content="width=device-width" />
<script src="@Url.Content("~/Scripts/angular.min.js")"></script>
<script type="text/javascript">
function myController($scope, $http) {
//若資料量很多的話,建議改用$http的Ajax方法撈資料指派給$scope的orders成員
$scope.orders = @Html.Raw(ViewData["orders"])
//取得商品總數量
$scope.GetTotalNum = function () {
var sum = 0;
for (var i = 0; i < $scope.orders.length; i++) {
sum += parseFloat($scope.orders[i].Num);
}
return sum;
}
}
</script>
</head>
<body ng-controller="myController">
<table border="1">
<thead>
<tr>
<th>編號</th>
<th>商品名稱</th>
<th>數量</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="o in orders">
<td>{{o.id}}</td>
<td>{{o.ProductName}}</td>
<td>
<input type="text" ng-model="o.Num" />
</td>
</tr>
</tbody>
<tbody>
</tbody>
</table>
<hr />
商品總數量:<input type="text" value="{{GetTotalNum()}}"/>
</body>
</html>
該注意的是,不能用ASP.net MVC的Razor語法來跑迴圈產生資料列tr,因為產生出來的input欄位就不知道ng-model該綁定哪個變數,隨便給的話又會變成動態產生變數
總計部份反而會算不出來
所以大概就是這樣囉~