Stopping inifinte scroll in ionic

So I am trying to implement infinite scroll in ionic , i have a ng-if on noMoreItemsAvailable . I see the console log, but the infinite scroll does not stop. I am new to both JS/ionic.

$scope.idx = 0;
$scope.noMoreItemsAvailable = true;
$scope.loadMore = function() {


  $scope.items.push($scope.items[$scope.idx++]);

  if ( $scope.items.length > 50 ) {
    console.log("Debug"+$scope.items[$scope.idx].name);
    $scope.noMoreItemsAvailable = false;
  }
  $scope.$broadcast('scroll.infiniteScrollComplete');

};

HTML:

<ion-infinite-scroll ng-if="noMoreItemsAvailable"
  on-infinite="loadMore()"
  distance="10%">
</ion-infinite-scroll>

For one, ngIf creates a child scope: if you use the chrome extension batarang and check that $scope.noMoreItemsAvailable === true, but $scope.noMoreItemsAvailable within ngIf's scope will likely be false--this is a common angular gotcha (see the canonical stack overflow answer for a thorough explanation, but short answer, because Javascript's prototypal inhereitance, that's why). Quick fix is to make .noMoreItemsAvailable an attribute on some object ($scope.myObj.noMoreItemsAvailable) which will fix your inheritance issues.

Also, because ngIf creates a child scope, <ion-infinite-scroll> may not be getting thescroll.infiniteScrollComplete event-- you can instead $emit it, $broadcast it from $scope.$parent, or do $rootScope.$broadcast, though most would probably consider the former the most concise. I haven't used that directive, so am not sure, but wouldn't be surprised if that were the case.

I may have fudged some detail in there, but bottom line: read about the angular 'the dot' gotcha, and know that ngIf create's a child scope!

I got this working, but I am not completely sure if I can explain why it does work.

I observed that this line was executed but items but was not being updated globally, not sure how best to explain it. Since locally within the function length of the items was increasing but it was not getting reflected in my html(ng-repeat).

$scope.items.push($scope.items[$scope.idx++]);

I added this line

$scope.$apply();

Now since I was feeding the static array's data back into it, it started throwing errors indicating that I can not add same object twice.

I fixed this by replacing the original 'push' by this

$scope.items.push(angular.copy($scope.items[$scope.idx++]));

Don't know the explanations for

  1. Without any other changes for inheritance purposes, "ng-if" is working and the scroll stops after 50 data points.
  2. Why did the length of items increase without really adding new items to array.

$timeout(function() { 
       $timeout(function() {
               $scope.$broadcast('scroll.infiniteScrollComplete');
               // call your ng-if to set to false
       });
  });

This works in the latest rc1 version of ionic.