将项添加到Angular数组
Add item to array Angular
我有一个包含以下字段的表:product
、lot
、input1
、input2
。您可以克隆一行,也可以添加新行。
我想做的是,对于每一行,您都可以添加一个新的Lot,该Lot由用户在Select lot
下的输入字段中写入的"number"answers"id"创建。我希望脚本在json数据和lot
的选项列表中添加新的Lot。
这是我尝试做的添加的功能:
$scope.addLot = function() {
var inWhichProduct = row.selectedProduct;
var newArray = {
"number": row.newLot.value,
"id": row.newLot.id
};
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i].selectedProduct === inWhichProduct) {
$scope.items[i].selectedLot.push(newArray);
}
}
};
-->>这<lt;--是完整的代码。
你能帮我吗?
我认为你的问题有点过于宽泛,无法在Stack Overflow上回答,但这里有一个尝试:
<div ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat="lot in lots">
<td>{{ lot.id }}</td>
<td>{{ lot.name }}</td>
</tr>
</table>
<p>name:</p> <input type="text" ng-model="inputName">
<p>id:</p> <input type="text" ng-model="inputId">
<button ng-click="addLotButton(inputId, inputName)">Add</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.lots = [{
name: "test",
id: 1
},
{
name: "test2",
id: 2
}
];
$scope.addLot = function(lotId, lotName) {
var newLotObject = {
name: lotName,
id: lotId
};
$scope.lots.push(newLotObject);
};
$scope.addLotButton = function(id, name) {
$scope.addLot(id, name);
};
$scope.addLot(3, "Another test");
});
</script>
基本上,这段代码只接受一些输入,并将一个对象添加到该输入的作用域中。该表是使用该数据的ng个重复创建的。这不是一个很好的代码,但它只是一个快速的例子。
push方法将newArray添加到selectedLot数组中。它不是在JSON数据上工作,而是在数组上工作。如果你想拥有JSON,你可以尝试一下:
var myJsonString = JSON.stringify(yourArray);
它将基于参数创建一个JSON字符串
也许你应该尝试构建你的数据结构,使批量成为产品的属性。
{
products: [
{id: 1, lots: [{id:1}, {id:2}]},
{id: 2, lots: [{id:1}, {id:2}]}
]
}
为产品添加大量:
product = products[0];
product.lots.push(newArray);
更改休耕:
html:
<button ng-click="addLot(row.selectedProduct.id,row.newLot.value,row.newLot.id)">Add</button>
js:
$scope.addLot = function(id,val,lotId) {
// console.log(id);
var inWhichProduct = id;
var newArray = { "value": val, "id": lotId };
//console.log($scope.items)
angular.forEach($scope.items,function(v,i){
if($scope.items[i].id == id )
{
$scope.items[i].lots.push(newArray);
console.log($scope.items[i].lots);
}
});
};
http://plnkr.co/edit/W8eche8eIEUuDBsRpLse?p=preview
相关文章:
- Javascript(Angular)从一个对象数组到第二个数组查找值
- Angular只从数组中获取所需的数据
- 算法:从数组(javascript/angular)中按当前日期获取上一个和下一个事件
- 向Angular作用域对象添加对象数组——TypeError
- 使用Angular.js解析JSON中的嵌套对象数组
- 获取Angular JS中的数组大小
- 使用Angular.js访问php数组数据
- 如何在 Angular JS 中从关联数组创建多个复选框
- 以angular.js显示数组
- Javascript或angular js中的对象数组
- 要筛选的数组的管道值的含义:$select.search in angular
- $scope$观察数组中的一个特定对象——Angular JS控制器
- 2D数组在Angular JS 1.2.x中工作,而不是在1.3.x中工作
- 如何在angular js/HTML中处理数组
- angular mongodb数组格式写错了
- 如何使用angular指令从html中获取数组
- Angular数组更改时更新HTML视图
- 将项添加到Angular数组
- 连接到ng-model的Angular数组值
- 在Angular数组上使用splice()时,jQuery选择器跳转到下一项