Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a list of item in to Angular JS array?

Tags:

angularjs

So we know the code below works:

  $http({ method: 'POST', url: url_getMoreHouse })
        .success(function (data) {
                    alert('Works');
                    console.log(data);

                       $scope.HouseBasket = data;
                });

However if we want to append the data into the current basket which is:

         $scope.HouseBasket += data;

This will cause errors, I dont want to use a foreach loop to push() each data into the $scope.HouseBasket is there a faster way to add a list of Object into the angular list?

like image 957
Ricc Avatar asked Sep 14 '14 21:09

Ricc


People also ask

How to add data into array in AngularJS?

Approach: In this approach, the push() method is used to insert the element at the end of the array. In the first example, a static value 'Geek' is inserted in the array and in the second example a input box is provided to the user to push the value they want.

How to push data into array in angular?

The push() method is a built-in method in AngularJS that inserts an object into an existing array. It takes two arguments: the object to push and the index of the position to insert the object. The first argument is the object that will be pushed into the array and should be of type string, number, boolean, or null.

How to push key and value in array in AngularJS?

The code you have above is pushing an array onto an array: var arrayForUse = []; arrayForUse. push({tag:$scope. tagsFeed, instructions:$scope.


1 Answers

is there a faster way to add a list of Object into the angular list

How big is your data ?, Well a simple for loop will not be slower that most possible solutions, but if your destination list is big enough you could use a while loop progressively popping(or shifting) out of the array and pushing to the destination.

$scope.HouseBasket += data; This will cause errors

You are looking for array.concat $scope.HouseBasket = $scope.HouseBasket.concat(data);


If you want to achieve this in one line you could :-

use function.apply to push a list at once to the source.

     [].push.apply($scope.HouseBasket, data);

or

     $scope.HouseBasket = $scope.HouseBasket.concat(data);
like image 164
PSL Avatar answered Oct 18 '22 06:10

PSL