【发布时间】:2017-07-01 13:38:43
【问题描述】:
我在 AngularJS 中编写了这段代码,我想在其中添加商品名称、价格和数量。该项目在下表中表示并保存为数组。后来,我找到了总帐单。
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<p>Try to add the items.</p>
<div ng-app="myApp" ng-controller="myCtrl">
<table border="1">
<tr>
<td>Item</td>
<td>Price</td>
<td>Quantity
</tr>
<tr>
<form>
<td><input type = "text" ng-model="name"></td>
<td><input type = "text" ng-model="price"></td>
<td><input type = "text" ng-model="quantity"></td>
</form>
</tr>
</table>
<br>
<button onClick="createItem()">Add to Cart</button>
<h2>My Cart</h2>
<div style="border: 1px solid blue;">
</div>
<table border="1" class="mytable">
<tr>
<td>S.No.</td>
<td>Item</td>
<td>Price</td>
<td>Quantity</td>
<td>Cost</td>
</tr>
<tr ng-repeat="item in items">
<td><span ng-bind="item.serial"></span></td>
<td><span ng-bind="item.name"></span></td>
<td><span ng-bind="item.price"></span></td>
<td><span ng-bind="item.quantity"></span></td>
<td><span ng-bind="item.cost"></span></td>
</tr>
</table>
<br>
<h3><span ng-bind="total"></span></h3>
</div>
<script>
var app = angular.module('myApp', []);
app.controller("OnlineShopping", function($scope)
{
var i = 1;
$scope.createItem = function($scope) {
var item = {};
item.serial = i++;
item.name = $scope.name;
item.price = $scope.price;
item.quantity = $scope.quantity;
item.cost = $scope.price * $scope.quantity;
item.cost = $scope.quantity;
addItem(item);
};
$scope.addItem = function(item) {
$scope.items.push(item);
$scope.item = {};
};
$scope.totalBill = function(items) {
$scope.total = 0;
for(var item in items) {
total+=item.cost;
}
$scope.total = total;
};
</script>
</body>
</html>
请指导我做错了什么,它不起作用,以及如何将此数组收集为对象以保存在数据库中。我不确定如何使用 angular 来实现这一点,每当有一个新的指令模板添加到动态视图时,如何将对象添加到数组中。
提前致谢。
【问题讨论】:
标签: javascript angularjs angularjs-directive controller angularjs-scope