0

I have a ng-repeat of divs, and when I try to access these divs on load, they don't exist yet. How do I execute a function when ng-repeat finishes? I tried directives, but they don't seem to work.

Zygimantas
  • 33,165
  • 6
  • 21
  • 23

1 Answers1

1

If the possible duplicate doesn't fulfil your needs here's a way to do it - Plunker.

JS

app = angular.module("app", []);

app.directive("test", [ function() {
    return {
        restrict: "E",
        template: "<div ng-repeat='item in ts.items track by $index' ng-init='ts.blah($index, $last)'>{{$index}}</div>",
        scope: {},
        controllerAs: "ts",
        bindToController: true,
        controller:function() {
          var ts = this;
          ts.items = [0, 1, 2, 3, 4];
          ts.blah = function(index, last) {
            console.log(index, last);
            if (last) {
              // Do your stuff
            }
          }
        }
    }
}]);

Markup

<!DOCTYPE html>
<html>

  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body ng-app="app">
    <test></test>
  </body>

</html>

The output from the console is:

0 false
1 false
2 false
3 false
4 true

so you should (in theory) be able to rely on the last repeat element being created last.

camden_kid
  • 12,591
  • 11
  • 52
  • 88