簡體   English   中英

將項添加到數組Angular

[英]Add item to array Angular

我有一個包含這些字段的表: productlotinput1input2 您可以克隆一條線,然后添加一條新線。

我想要做的是,對於每一行,您可以添加由“數字”和“id”創建的新批次,用戶在“選擇lot下的輸入字段中寫入。 希望腳本在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);
        }
    }
};

- >> 這個 << - 是完整的代碼。

你能幫助我嗎?

我認為您的問題在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-repeat創建的。 它根本不是很好的代碼,但它只是一個簡單的例子。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM