将元素推入数组时,重复使用相同的元素替换前一个元素

时间:2017-07-08 07:41:52

标签: javascript angularjs arrays

我在角度js中创建动态表单,当我将新输入字段添加为表格行时,将这些对象推送到数组中时,前一个元素将替换为新元素的副本。键是相同的,但值是不同的,并且还添加了' id'在推入阵列之前键。

JS
else if (el.type === 4) { //table   
 var x = 0;
 $scope.row = []; //to store KEY OF  table
 $scope.thead = []; //store the heading of the table | also to make row      structure
 $scope.myFm[el.value] = []; //store row of table [ INVOICE ] myFm.invoice
 $scope.colInput = {}; //values of input of each row
 $scope.colInput.id = 0;
 $scope.rowIndex = 0;
 //iterate over column_heading
 el.column_heading.forEach(function(elem) { //objects in column_heading
    $scope.row[x] = elem.val; //the object with key names of row
    $scope.thead.push(elem); //column headings
    x++;
 })
 //pusing each row to myFm[el.value] | invoice
 $scope.addNew = function(rowObj) {
    // $scope.rowIndex++;
    console.log('ROW ', rowObj);
    rowObj.id = $scope.rowIndex;
    $scope.myFm[el.value].push(rowObj);
    console.log("Invoice", $scope.myFm[el.value]);
    $scope.rowIndex++;
    console.log("ROW", rowObj);
 }

 var row = "<tr ng-repeat='r in myFm." + el.value + " track by id' ><td ng-repeat='i in row'><input ng-model='colInput[i]' class='form-control' placeholder='Enter {[{ i }]}'></td></tr>"

  item = "<label>" + el.heading + "<button ng-click='addNew(colInput)' class='m-l-lg btn font-bold'>ADD NEW</button></label>  <table class='table'><thead><th ng-repeat='th in thead'>{[{ th.name }]}</th><thead>" + "<tbody>" + row + "</tbody><table>";
}
return item
}
// adding each element from list to DOM. $compile is needed to add the     modified element to DOM
$scope.data.forEach(function(el) { //traversing over json object from the   server                 
  var item = verifyItem(el);
  var linkFn = $compile(item);
  var content = linkFn($scope); 
  element.append(content);
});
// adding the submit button to DOM
var linkFn = $compile('<button type="submit" ng-click="submitFm()"  class="m- t-lg m-b-lg btn btn-danger">Submit </button>');
var content = linkFn($scope);
element.append(content);

当我通过&#39; colInput&#39;添加新的&#39;功能,并添加&#39; id&#39;每当我将新对象推送到数组&#; $ scope.myFm [el.value]&#39;时,都会创建重复项,即:新添加的正在替换先前的对象,因此我无法解决问题。 NG-重复&#39;它通过id&#39;跟踪。

CONSOLE

Invoice Array [ Object, Object, Object ]

这三个对象具有最后推送对象的值。

我该如何修复它。

0 个答案:

没有答案