Nahiduzzaman Rose Nahiduzzaman Rose - 4 months ago 8
AngularJS Question

How can I push element in an array whenever a function get called?

I am implementing infinite scroll. I Have an array named

hotels
which gets data from
$http.get()
method. Now I want to populate a new array named
hotelsNew[]
with the value of
hotels
array
. But I want to push value in the
hotelsNew
incrementing value of m and j. The value of m and j need to be updated (increment) whenever function loadMore() is called. Initial value of m is 0 and j is 5. When loadMore() get called again m will be 5 and j will be 10 and so on. I am unable to save value of m and j anywhere because
$http.get()
is asynchronous. Is there any proper way to save values of m and j , and reuse it when
loadMore()
get called again?. Maximum j value is 40. and when m = j(40) ,it will stop.

Here is my controller code.

$scope.loadMore = function() {
$http.get(url).success(function(data, status, headers, config) {
if(data) {
$scope.hotels = data.hotels;
for(var i = m; i < j; i++) {
console.log('i=',i);
$scope.hotelsNew.push($scope.hotels[i]);
console.log('hotelsNew',$scope.hotelsNew);
}
}
}


How can i increment m and j value ?any idea?

Answer

If m and j increments same amount each time, you can create a local variable in your controller.

var m = 0, j = 5;
$scope.loadMore = function() {
    $http.get(url).success(function(data, status, headers, config) {
        if(data && j < 40) { 
            $scope.hotels = data.hotels;
            for(var i = m; i < j; i++) {
                console.log('i=',i);
                $scope.hotelsNew.push($scope.hotels[i]);
                console.log('hotelsNew',$scope.hotelsNew);
            }
            m += 5;
            j += 5;
        }
    }
}