-3

This is a just a temp code. I want a function to be called when the last element of ng-repeat is visible on screen.

window.app = angular.module('testApp', []);

app.controller("myCtrl", function($scope) {
    $scope.properties = [
        {name:"Alfreds Futterkiste"},
        {name:"Berglunds snabbköp"},
        {name:"Centro comercial Moctezuma"},
        {name:"Ernst Handel"},
        {name:"Alfreds Futterkiste"},
        {name:"Berglunds snabbköp"}
       
    ]
})
.style{height:20px;margin:5px;background-color:#f5f5f5; padding:10px}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="testApp" ng-controller="myCtrl">
<div ng-repeat="prop in properties" class="style">
  <p>{{prop.name}}</p>
</div>
<!--I-want-to-call-a-function-at-the-last-element-of-ng-repeat-when-visible--> 
</div>
Santosh
  • 15
  • 5

1 Answers1

-1

Use a directive to handle the last looped item, when $last you could call a function.

VIEW

<!-- application container -->
<div ng-app="app" ng-controller="demoController">

  <div ng-repeat="item in dataItems" my-repeat-directive>
    loop item : {{item}}
  </div>

</div>

CONTROLLER / DIRECTIVE

angular
.module('app', [])

.controller('demoController', function($scope){
    $scope.dataItems = [
    {'id' : 1, 'name' : 'test1'},
    {'id' : 1, 'name' : 'test1'},
    {'id' : 1, 'name' : 'test1'}
  ];

  $scope.callFunction = function(){
    alert('function called');
    console.log('function invoked');
  }

})

.directive('myRepeatDirective', function() {
  return function(scope, element, attrs) {
    if (scope.$last){
      console.log('last item');
      window.alert("im the last!");
      scope.callFunction();
    }else{
        console.log('not last item');
    }
  };
})

OR

Or Call the function using prebuilt Angular ng-if and ng-initdirectives. Although it's pretty dirty... It should also work.

<div ng-repeat="item in dataItems" my-repeat-directive>
  loop item : {{item}}
  <div ng-if="$last" ng-init="callFunctionInit()">last</div>
</div>


$scope.callFunctionInit = function(){
  alert('function called on view');
  console.log('function called on view');
}

JSFIDDLE

daan.desmedt
  • 3,752
  • 1
  • 19
  • 33
  • I want to call the function when the last element is visible on screen not after it has rendered. – Santosh Jun 26 '17 at 10:10