user7176666 user7176666 - 15 days ago 9
AngularJS Question

Dynamically Adding Similar Objects

I'm trying to push similar objects into an array and in each object I'm pushing some values, but the values updated are reflecting in all objects. I want to add only three values from the foo array into the 1st object and other 3 in foo of second object, but in both the objects, all six values are appearing.

<!DOCTYPE html>
<html ng-app="myApp" ng-controller='myCtrl'>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
myapp=angular.module('myApp',[]).controller('myCtrl',function($scope){
$scope.inp=[];
var a={foo:[]};
var barcode='one_two_three_four_five_six';
var arr=barcode.split('_'),k=-1;
for(i=0; i < arr.length; i++){
if(i%3 == 0){
$scope.inp.push(a);
k++;}
$scope.inp[k].foo.push(arr[i]);
}
});
</script>
<body>
<div ng-repeat='x in inp track by $index'>{{(x)}}</div>
</body>
</html>

Answer

Have a temporary array variable to hold the 3 values and push that value to foo array

var temp=[];
for(i=0;i<arr.length;i++){
    temp[i%3]=arr[i];
    if((i+1)%3==0){
        foo.push(temp);
        temp=[];
        k++;
    }
}