Im working on angular 1, creating a Component which will have 2 buttons ADD and Remove. On ADD click it should push a new object to the array. When i click on ADD the row is created correctly, but if you click on ADD again, it will copy the previous object, instead of creating one.
In the component i need to send an array of objects, and the pattern of the array i want to push (arrays structure lookalike when pushing to another items).
https://plnkr.co/edit/zI3MdoqyBjGcXd30hPsS?p=preview
Code:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.itemsObj = [{
id: 1,
name: 'JayZ'
}, {
id: 2,
name: 'Mc'
}]
$scope.pushItem = {
id: null,
name: null
}
});
app.component('addRemoveRow', {
templateUrl: './addRemoveRow.html',
bindings: {
pushObj: "<", // we pass here objects structure ( given pattern )
index: "<", // this is the index of the array
obj: "=" // this is the list of the items where we push pushObj
},
controller: function($timeout) {
var ctrl = this;
ctrl.$onChange = function(value) {
console.log(value);
ctrl.obj = ctrl.obj;
};
ctrl.addRow = function(event) {
console.log(ctrl.pushObj);
ctrl.obj.push(ctrl.pushObj);
};
ctrl.deleteRow = function(event) {
ctrl.obj.splice(ctrl.index, 1);
};
}
});
html:
<div>
<button class="btn btn-xs btn-success mb10 block"
ng-click="$ctrl.addRow($event)">
ADD
</button>
<button class="btn btn-xs btn-danger mb10 block"
ng-show="$ctrl.obj.length > 1"
ng-click="$ctrl.deleteRow($event)">
Remove
</button>
</div>
To see better what i mean, in the plunker, add a row, type something in the inputs, and add another row, when you add the new row it will look the same as previously which should not. it should match the given pattern in pushObj
You're passing reference of object each time when you are pushing object into array. So thats why same reference has been placed into array element. and once its property gets changed it will reflect wherever its reference is there.
You should clone the object before pushing inside array using
angular.copy
(clone object will have new reference).Demo Plunkr