0

I am splicing a list of phone types. I have an original list defined by $scope.phoneTypeList. In my actual app I'm obtaining the list through AJAX but I've defined it as an object for this example.

I then have an empty list called $scope.addPhoneType. I assign the data from phoneTypelist into $scope.addPhoneType then run a for loop. The for loop takes an array of a users phone types. If it is in the list it will splice the addPhoneType. Eg if the user has DEFAULT it will remove it from addPhoneType.

The issue I'm having is when I splice the addPhoneType it also splices phoneTypeList. That is for the example phoneTypeList becomes =["DDI", "MOBILE","FAX"] where it shouldn't be touched at all.

It's like its binded to addPhoneType. I've never come across this before? Is this normal behaviour? Does anyone have a work around? Thanks in advance, any advice appreciated.

My Code:

$scope.editCompany = function(){
      $scope.phone = [{phone_type_id:"DEFAULT",number:"1123"}]
      $scope.phoneTypeList = ["DDI", "DEFAULT", "MOBILE","FAX"];
      $scope.addPhoneType =[];
      $scope.addPhoneType = $scope.phoneTypeList;
      for (x=0;x<$scope.phone.length;x++){
         var phoneType = $scope.phone[x].phone_type_id;
         var index = $scope.addPhoneType.indexOf(phoneType);
         if (index >= 0){
         $scope.addPhoneType.splice(index,1);     
         }
      }
      console.log($scope.phoneTypeList);
   }
Ka Tech
  • 8,937
  • 14
  • 53
  • 78

2 Answers2

1

This

$scope.addPhoneType = $scope.phoneTypeList

will actually create a reference of the array to a new variable and not just copy the contents of phoneTypeList array to addPhoneType.

If you want to copy the contents you can use:

var newArray = oldArray.slice();

(in your case $scope.addPhoneType = $scope.phoneTypeList.slice();)

Ref:

Community
  • 1
  • 1
trainoasis
  • 6,419
  • 12
  • 51
  • 82
  • Thank you so much for explaining the issue. It makes sense now. I end up using angular.copy but again appreciate the answer. – Ka Tech May 09 '15 at 11:55
1

The behavior you see is completely normal, since non-primitives are 'passed by reference' in javascript. Please checkout this question and its answers - Setting one object equal to another object with the assignment operator in Javascript

To avoid this situation you could try using angular.copy (https://docs.angularjs.org/api/ng/function/angular.copy), which would create a deep copy of your destination object into source and thereby dereferencing the destination.

Please refer this link for more information - http://weblog.west-wind.com/posts/2013/Sep/16/JavaScript-Arrays-References-and-Databinding-in-Angular

Community
  • 1
  • 1
user700284
  • 13,540
  • 8
  • 40
  • 74
  • Thank you for the extra information and the answer. I end up using angular.copy and works. But most of all it is a new concept I've learnt which is really important to know. Thanks again. – Ka Tech May 09 '15 at 11:56