MaTaDoRcpe MaTaDoRcpe -4 years ago 42
AngularJS Question

Angularjs add new data to array

I want to add the new data into the array variable, but the thing is, the new data is inserted it to overwrite existing data already exist.
I need to fix?

HTML Code:

<ion-view title="แจ้งสัตว์เกิด" id="page4">
<ion-content padding="true" class="has-header">
<form id="page4-form3" class="list">
<label class="item item-select" id="page4-select5">
<span class="input-label">ประเภท</span>
<select name="selectCategory" id="selectCategory" ng-model="form.categoryID" ng-change="getType(form.categoryID)">
<option ng-repeat="recordCategory in myDataArrayCategory" value="{{recordCategory.aCategory}}">{{recordCategory.aCategoryName}}</option>
<label class="item item-select" id="page4-select6">
<span class="input-label">ชนิด</span>
<select name="selectType" id="selectType" ng-model="form.typeID">
<option ng-repeat="recordType in myDataArrayType" value="{{recordType.aType}}">{{recordType.aTypeName}}</option>
<label class="item item-input" id="page4-input5">
<span class="input-label">จำนวน</span>
<input type="number" ng-model="form.Amount" placeholder="">
<button id="page4-button2" class="button button-positive button-block" ng-click="addData(form)">เพิ่ม</button>
<ion-list id="page4-list3">
<ion-item id="page4-list-item4">Item</ion-item>
<button id="page4-button3" class="button button-positive button-block">บันทึก</button>

JS Code:


.controller('addDataCtrl',function ($scope,$http) {

$scope.form = {

$scope.arrData = [];

$scope.addData = function (arrInput) {


I have to fix it?
Do I need to do to add new data into variables Array won't overwrite the original.

Answer Source

Your original value is getting overwritten due to shallow copy of the array .Actually when we use '=' for assignment, the new variable and old variable refers to the same memory location , hence if you modify one the value of other will also get modified .

Solution for this - use deep copy using angular.copy(source,destination) as below -

$scope.addData = function (arrInput) {
var deepCopy= {};
angular.copy(arrInput, deepCopy);

Please check this copy-and-assignment link for more details. Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download