2

What's the best way to force a digest in Angular when using events outside of Angular itself - for example when loading an image in a jqLite container, I find myself doing this:

$img.on('load', function () {
    $timeout(function () { // Force digest
        $scope.isLoaded = true;
    });
});

This is a pattern I find myself using a lot. However it feels very dirty (like a hack-dirty, ugh). However, using $apply() might trigger a "digest already in progress" error. I know I could check for $scope.$$phase, but that feels equally dirty.

So, what's the correct way to get your changes to the DOM as fast as possible?

Community
  • 1
  • 1
Laust Deleuran
  • 492
  • 1
  • 5
  • 19
  • *"I find myself using a lot"*. Ideally you shouldn't need to use it often, so maybe you app design could be improved in the first place. – dfsq Nov 09 '15 at 20:13
  • @dfsq Yeah, I know that phrase is kinda vague. "_A lot_" usually translates to whenever I'm working with some kind of external event system, such as (jqLite) DOM events. If I'm reading [this answer correctly](http://stackoverflow.com/a/18626099/799327), then that's exactly the correct use-case. It just still feels, well, ugly. – Laust Deleuran Nov 09 '15 at 22:53

1 Answers1

1

You can use $scope.$evalAsync() instead. This will also potentially give you better performance because the action might be performed in the already initiated digest.

Reference: $scope.$evalAsync() vs. $timeout() In AngularJS

Mike McLin
  • 3,627
  • 7
  • 41
  • 49