Я создаю форму с добавлением новой функции строки. Я могу создать новую строку динамически, но проблема в том, что я не могу отобразить начальное значение в своих текстовых блоках.
Вот некоторые из моего кода:
<div class="row" ng-app="product_list">
<div class="table-responsive" ng-controller="productList">
<table class="table table-bordered table-hovered">
<thead>
<tr>
<td class="text-left">Product Name</td>
<td class="text-left">Quantity</td>
<td class="text-left">Price</td>
<td class="text-left">Subtotal</td>
<td class="text-center"><button type="button" class="btn btn-default" ng-click="addNewRow()">Add Row</button></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="value in product.item">
<td class="text-left">
<input type="text" ng-model="item.name" class="form-control" />
</td>
<td class="text-center">
<input type="number" ng-model="item.quantity" class="form-control" />
</td>
<td class="text-right">
<input type="number" ng-model="item.price" class="form-control text-right" value="{{ value.price }}" />
</td>
<td>{{ item.price * item.quantity | currency }}</td>
<td class="text-center">
<button type="button" class="btn btn-danger" ng-click="removeRow($index)">Remove</button>
</td>
</td>
</tbody>
<tfoot>
<tr>
<td colspan="3">
<td colspan="3" class="text-left">
<label>Subtotal: </label>
<input type="text" class="form-control text-right" value="{{ total() | currency }}" readonly />
</td>
</tr>
</tfoot>
</table>
</div>
</div>
JS:
<script type="text/javascript">
var appList = angular.module('product_list', []);
appList.controller('productList', function($scope){
$scope.product = {
item: [
{
product_name: 'Test name 1',
quantity: 5,
price: 99.9,
}
]
};
$scope.addNewRow = function() {
$scope.product.item.push({
product_name: '',
quantity: 1,
price: 0
});
}
$scope.removeRow = function(index) {
$scope.product.item.splice(index, 1);
}
$scope.total = function() {
var total = 0.00;
angular.forEach($scope.product.item, function(item){
total += item.quantity * item.price
});
return total;
}
});
</script>
Здесь plnkr: http://plnkr.co/edit/6vAVPw?p=preview
У вас есть переменные, которые несовместимы, здесь вы используете value
как повторяющийся элемент:
<tr ng-repeat="value in product.item">
Но тогда вы используете элемент как item
, так что просто измените свое value in product.item
на item in product.item
:
<tr ng-repeat="value in product.item">
Также обратите внимание, что в строке 44 HTML у вас есть недопустимый html, измените </td>
на </tr>
Последнее, что нужно заметить, это то, что имя переменной вашего объекта называется product_name
в ваших объектах, но вы назначаете item.name
вашей ng-model
. Так же обновите свое первое текстовое поле до ng-model=item.product_name
Это связано с тем, что вы используете другое имя переменной в ng-repeat и ng-model
<tr ng-repeat="value in product.item">
Поскольку вы используете ng-model = " item.name", просто замените значение на элемент
как это
<tr ng-repeat="item in product.item">