Getting an item inside ng-init and ng-repeat

I am trying to use ng-init to initialize when loading a specific item. In my template, I do this:

<div id="timer-0" ng-init="initTimer('timer-0', timerOne);"></div> 

timerOne is an object declared in a controller scope that looks something like this:

 $scope.timerOne = {...}; $scope.initTimer = function(id, timer) { var element = angular.element("#"+id); // a bunch of other stuff with the timer and element interacting with each other } 

Everything works fine when my HTML is hardcoded this way, but when I start trying to call initTimer inside ng-repeat, angular.element returns nothing.

My ng-repeat looks like this:

 <div ng-repeat="timer in timers"> <h1>{{timer.label}}</h1> <div id="timer-{{$index}}" ng-init="initTimer('timer-'+$index, timer);"></div> </div> 

I assume the elements are inserted into the DOM after calling ng-init. Is there a way to call my init function as soon as I'm sure that these elements exist?

+1
source share
1 answer

Just pass the index as a parameter in the init function.

 <div ng-repeat="timer in timers"> <h1>{{timer.label}}</h1> <div id="{{'timer-'+$index}}" ng-init="initTimer($index, timer);"></div> </div> 

And in the controller, try accessing the element as follows:

 $scope.initTimer = function(id, timer) { var element = angular.element('timer-' + id); } 
+1
source

All Articles