Search code examples
javascriptangularjsangularjs-scope

Angular 1.5 - How to add element to a scoped array


I have an Angular controller that defines a scoped variable that consist of an array of objects. Each object is a tagName and its value is a list of services associated to those tags:

$scope.recordedServices = [{"myTag" : [{ url : "http://service0"}, { url : "http://service1" }] }]; 

After the page is loaded {{recordedServices}} prints correctly:

[{"myTag":[{"url":"http://service0"},{"url":"http://service1"}]}]

In that controller I have a replaceList function that replaces the whole $scoped.recordedServices list:

  $scope.replaceList = function(){
      $scope.recordedServices = [ {"myTag" : [{url:"http://replacedList"}] }];
  }

When calling it, everything works as expected, {{recordedServices}} is now:

[{"myTag":[{"url":"http://replacedList"}]}]

Now the problem. What I really want to do is add a new service to "myTag":

  $scope.addToList = function(){
      $scope.recordedServices["myTag"].push({url:"http://addedService"});
  }

But it fails because $scope.recordedServices["myTag"] doesn't exist, the actual structure of the $scoped.recordedServices list is:

$scope.recordedServices: Array[1]
0 : Object
  $$hashKey : "object:33"
  myTag : Array[1]
    0 : Object
      $$hashKey : "object:36"
      url : "http://replacedList"

What is the correct (Angular) way to add an element to that array?

UPDATE:

One possible solution would be doing:

 $scope.addToList2 = function(){
      if($scope.recordedServices[0] == null){
          $scope.recordedServices[0] = [];
      }
      if($scope.recordedServices[0]["myTag"] == null){
          $scope.recordedServices[0]["myTag"] = [];
      }
      $scope.recordedServices[0]["myTag"].push({url:"http://addedService"});
  }

But this works only if $scope.recordedServices was initialized in the controller (for instance: $scope.recordedServices = [{"myTag" : [{ url : "http://service0"}, { url : "http://service1" }] }];). However if initially it is $scope.recordedServices = [] it doesn't work.

{{recordedServices}} prints [[]]

Inspecting the variable the content is as follows. It looks similar with the only differenced that myTag[0] doesn't contain $$hashKey.

$scope.recordedServices: Array[1]
0 : Array[0]
  $$hashKey : "object:68"
  length : 0
  myTag : Array[1]
    0 : Object
      url : "http://addedService"

Solution

  • $scope.recordedServices is an array. You should use an index:

    Change this:

    $scope.recordedServices["myTag"].push({url:"http://addedService"});
    

    to this:

    $scope.recordedServices[0]["myTag"].push({url:"http://addedService"});
    

    UPDATE

    You can check if it is empty, if so, add myTag object too:

    if ($scope.recordedServices.length == 0){
        $scope.recordedServices.push({"myTag": [{url:"http://addedService"}]});
    }else{
        $scope.recordedServices[0]["myTag"].push({url:"http://addedService"});
    }