1

I'm building an app in AngularJS. My app also uses a third party javascript library that acts on a div like this one:

<div id="turn-me-into-a-slider"></div>

Now I actually have several of these divs, and use an ng-repeat to make them. So it really looks more like this:

<div id="sliders-container" ng-repeat="slider in sliders track by $index">
    <div id="slider-{{$index}}"></div>
</div>

Now in my code, when I want to add a slider first I add a new slider to the sliders array. That should propagate into the DOM and then I can run the initialization function for the slider on the div with id="slider-n". This is where the problem comes in. If I put the initialization function for the slider right after pushing a new value onto the sliders array, the DOM hasn't updated yet, and when the slider initializer is called, there is no DOM element with the proper id yet, and initialization fails. If I call $scope.$apply() first, that fixes the problem, but occasionally I get a error, $scope.$apply() already in progress. Is there a way I can call $scope.$apply() only when it's not currently running to avoid this? If you have any other suggestions, I'd welcome them.

user3413723
  • 11,147
  • 6
  • 55
  • 64

1 Answers1

0

Try this:

setTimeout(function() {
  $scope.$apply(/**your function*/);
}, 1000);

More explained in here: Why is using if(!$scope.$$phase) $scope.$apply() an anti-pattern?

Community
  • 1
  • 1
Jesús Quintana
  • 1,803
  • 13
  • 18
  • I need $scope.$apply() to be run immediately, because the next line depends on the DOM being updated. – user3413723 Feb 18 '15 at 13:09
  • You can use $$phase, like the article but not all the going to execute the apply, other option is evalAsync, but affect the performance (i think....), or the other way is change 1seconds to 1miliseconds, try the best for your case. – Jesús Quintana Feb 18 '15 at 13:36