0

I have this piece of code

if ($scope.newLeverAdded) {
    console.log("executed this");
    console.log($scope.tradeDataObj, "data is here");
    console.log($scope.group_levers, "this 2 here");
    $scope.group_levers.levers.push.apply($scope.group_levers.levers, $scope.tradeDataObj.levers[0]);

    console.log($scope.group_levers, "mid prrinting");
    console.log("after this");
}
console.log($scope.group_levers, "final prrinting");

All i am trying is to increase my Array size by adding new element to it.. SO that now the array contains 2 element. But the final console still returns a single element in array.

Why is it so?

Aracthor
  • 5,757
  • 6
  • 31
  • 59
Saurabh Tiwari
  • 4,632
  • 9
  • 42
  • 82
  • What is your complete console output? – Aracthor Oct 04 '15 at 05:12
  • 2nd argument to `apply` need to be an array. Is `$scope.tradeDataObj.levers[0]` is an array? –  Oct 04 '15 at 05:16
  • Why are you using `apply`? Is there a specific reason for that? –  Oct 04 '15 at 05:19
  • No..there is no specific reason. All I need is to preserve previous array data and push new data..so that I can send complete JSON back to server. I would really appreciate if some one could illustrate when is the need for .apply() withpush – Saurabh Tiwari Oct 04 '15 at 07:14

2 Answers2

1

Without being able to run your code, here's a couple of things you can try:

  1. it could be that your code is not entering the condition that you have specified.
  2. why not just test with a $scope.group_levers.levers.push('new element') instead of the apply
filype
  • 8,034
  • 10
  • 40
  • 66
1

I think you need:

$scope.group_levers.levers.push.apply($scope.group_levers.levers, $scope.tradeDataObj.levers);

The second argument of apply() should be an array.

I assume that you are trying to push multiple items like this and this

Community
  • 1
  • 1
Mohayemin
  • 3,841
  • 4
  • 25
  • 54
  • Mohayemin..thanx for pointing to right direction. I guessed, if the original source is array, only object should be added to it not the array again. Hence was doing levers[0]. Is this specifically the case fr apply – Saurabh Tiwari Oct 04 '15 at 05:37