问题
I'm trying to use ng-init to do some initialization when a particular element loads. In my template, I'm doing this:
<div id="timer-0" ng-init="initTimer('timer-0', timerOne);"></div>
timerOne is an object declared in the controller's scope, which 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 hard-coded like that, but when I start trying to call initTimer inside an ng-repeat, angular.element is returning 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'm guessing that the elements are getting inserted into the DOM after ng-init is called. Is there any way to call my init function once I know for sure these elements exist?
回答1:
Just pass index as 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 controller try to access the element like this:
$scope.initTimer = function(id, timer)
{
var element = angular.element('timer-' + id);
}
来源:https://stackoverflow.com/questions/28080352/getting-an-element-inside-ng-init-and-ng-repeat