如何在显示ng-repeat的最后一个元素时调用函数

时间:2017-06-26 09:26:40

标签: angularjs angularjs-ng-repeat

这只是一个临时代码。 我希望在屏幕上显示ng-repeat的最后一个元素时调用一个函数。

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>

1 个答案:

答案 0 :(得分:-1)

directive您可以调用某个函数时,使用$last来处理上一个循环项。

查看

<!-- 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');
    }
  };
})

或者使用预建的Angular ng-ifng-init指令调用该函数。虽然它很脏但它也应该有效。

<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