12

I am having an object like this $scope.releases = [{name : "All Stage",active:true}];

I need to append more data to it

[
  {name : "Development",active:false},
  {name : "Production",active:false},
  {name : "Staging",active:false}
]

So the final data should be like this

[
   {name : "All Stage",active:true}
   {name : "Development",active:false},
   {name : "Production",active:false},
   {name : "Staging",active:false}
]

I tried the following code. But it is not appending.

app.controller('MainCtrl', function($scope) {
  // I am having an object like this
  $scope.releases = [{name : "All Stage",active:true}];
  // I need to appned some more data to it
  $scope.releases = [
    {name : "Development",active:false},
    {name : "Production",active:false},
    {name : "Staging",active:false}
  ]
});

Pluker Link : http://plnkr.co/edit/gist:3510140

3 Answers 3

18
  $scope.releases = [{name : "All Stage",active:true}];
  // Concatenate the new array onto the original
  $scope.releases = $scope.releases.concat([
    {name : "Development",active:false},
    {name : "Production",active:false},
    {name : "Staging",active:false}
  ]);
Sign up to request clarification or add additional context in comments.

2 Comments

when i am trying this i got the following error TypeError: $scope.releases.concat is not a function
@Ambal Mani - $scope.releases is not an array at the point you're trying to call concat on it. What's the result of typeof($scope.releases) ?
5

Just use the Array concat method

$scope.release = [{name : "All Stage",active:true}];
$scope.releases = [
    {name : "Development",active:false},
    {name : "Production",active:false},
    {name : "Staging",active:false}
];
$scope.releases = $scope.releases.concat($scope.release);

Comments

1

user angular.extend() to extend the object angular extend

you can also use angular.merge() angular merge

2 Comments

useful for merging object and not just arrays in a simple way. voted up because of usefulness even if sightly ot
angular merge is now deprecated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.