我如何使用AngularJS在表格中包含和删除产品列表? 我在选择列表中选择一个产品,并设置金额,然后单击添加,以添加到表中。
HTML:
<label>Select a product</label>
<select>
<option>select...</option>
<option>value 1</option>
<option>value 2</option>
<option>value 3</option>
<option>value 4</option>
<option>value 5</option>
</select>
<br>
<label>Amount</label>
<input type="text" name="amount">
<button type="button">ADD</button>
<br>
<table>
<thead>
<tr>
<td>Product</td>
<td>Amount</td>
<td>Remove</td>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td><a href="">x</a></td>
</tr>
</tbody>
</table>
CSS:
table {
width: 50%;
}
table thead {
background-color: green;
color: #fff;
font-family: arial;
}
table tbody {
background-color: #ddd;
}
答案 0 :(得分:1)
首先,您需要创建一个控制器。
https://docs.angularjs.org/api/ng/directive/ngController
您需要在控制器中创建一个方法,将项目和数量推送到数组。通过以下方式将该功能分配给您的按钮:
https://docs.angularjs.org/api/ng/directive/ngClick
在你的html中,你需要循环你的数组,以便将你的记录添加到表格。
https://docs.angularjs.org/api/ng/directive/ngRepeat
你要问的事情有很多事情需要做。请查看文档,如果您不理解或面对错误,可以再次询问。
答案 1 :(得分:0)
<script>
angular.module("myApp", ['ngResource'])
.controller("myCtrl", function ($scope) {
$scope.products = [
{name: "apple", amount: "111"},
{ name: "orange", amount: "222"}
];
$scope.addProduct = function () {
$scope.products.push({name: $scope.myModel1, amount: $scope.myModel2, })
}
$scope.removeProduct = function (productToRemove) {
var index = $scope.products.indexOf(productToRemove);
$scope.products.splice(index, 1);
}
})
</script>
<!doctype>
<html>
<head>
<title>Test</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular-resource.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<label>Select a product</label>
<select ng-model="myModel1">
<option>select...</option>
<option>value 1</option>
<option>value 2</option>
<option>value 3</option>
<option>value 4</option>
<option>value 5</option>
</select>
<br>
<label>Amount</label>
<input type="text" name="amount" ng-model="myModel2">
<button type="button" ng-click="addProduct()">ADD</button>
<br>
<table>
<thead>
<tr>
<td>Product</td>
<td>Amount</td>
<td>Remove</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in products">
<td>{{product.name}}</td>
<td>{{product.amount}}</td>
<td ng-click="removeProduct()"><a href="#">X</a></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>