在 ng-init 和 ng-repeat 中获取一个元素 [英] Getting an element inside ng-init and ng-repeat
问题描述
我正在尝试使用 ng-init 在特定元素加载时进行一些初始化.在我的模板中,我这样做:
<div id="timer-0" ng-init="initTimer('timer-0', timerOne);"></div>
timerOne 是一个在控制器作用域中声明的对象,它看起来像这样:
$scope.timerOne = {...};$scope.initTimer = function(id, timer){var element = angular.element("#"+id);//一堆其他东西,定时器和元素相互交互}
当我的 HTML 像这样硬编码时,一切正常,但是当我开始尝试在 ng-repeat 中调用 initTimer 时,angular.element 什么都不返回.
我的 ng-repeat 看起来像这样:
<h1>{{timer.label}}</h1><div id="timer-{{$index}}" ng-init="initTimer('timer-'+$index, timer);"></div>
我猜测在调用 ng-init 之后元素会被插入到 DOM 中.一旦我确定这些元素存在,有没有办法调用我的 init 函数?
在 init 函数中传入 index 作为参数即可.
<h1>{{timer.label}}</h1><div id="{{'timer-'+$index}}" ng-init="initTimer($index, timer);"></div>
并在控制器中尝试像这样访问元素:
$scope.initTimer = function(id, timer){var element = angular.element('timer-' + id);}
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?
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屋!