在ng-init和ng-repeat中获取元素 [英] Getting an element inside ng-init and ng-repeat
问题描述
我正在尝试使用ng-init在加载特定元素时进行一些初始化.在我的模板中,我正在这样做:
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是在控制器范围内声明的对象,看起来像这样:
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
}
当我对HTML进行这样的硬编码时,一切都很好,但是当我尝试在ng-repeat中调用initTimer时,angular.element不返回任何内容.
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.
我的ng-repeat看起来像这样:
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>
我猜想在调用ng-init之后,元素将被插入到DOM中.一旦我确定这些元素存在,是否可以调用我的init函数?
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?
推荐答案
只需将索引作为init函数中的参数即可.
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);
}
这篇关于在ng-init和ng-repeat中获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!