Getting an element inside ng-init and ng-repeat

狂风中的少年 提交于 2019-12-13 02:23:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!