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.
Asked
Active
Viewed 137 times
0
-
Check for `$last` property inside `ng-repeat` loop. When it's set, you can execute the function – mohamedrias Apr 03 '15 at 07:22
-
4Possiblly duplicate of http://stackoverflow.com/questions/15207788/calling-a-function-when-ng-repeat-has-finished – squiroid Apr 03 '15 at 07:22
-
@squiroid I tried that method, it didn't work. Mohamedrias, how would I do that? could you give me an example? – Zygimantas Apr 03 '15 at 07:26
-
Is the function available in correct scope? you can run easily when $last is true – Samir Das Apr 03 '15 at 07:34
-
Here's the code: http://pastebin.com/buQmxsek – Zygimantas Apr 03 '15 at 07:36
-
Just a sample : http://jsbin.com/pobiyaqoca/1/edit?html,js,output @ZygimantasMagelinskas – mohamedrias Apr 03 '15 at 07:46
-
HTML - http://pastebin.com/MEKkCRj9 – Zygimantas Apr 03 '15 at 07:50
-
JS - http://pastebin.com/gEBiXp46 – Zygimantas Apr 03 '15 at 07:51
-
Doesn't call alert("ria") – Zygimantas Apr 03 '15 at 07:51
-
Maybe you could use watch$ functionality with conditionals? – Igor Apr 03 '15 at 07:55
-
How would I do that ? – Zygimantas Apr 03 '15 at 08:08
1 Answers
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