Wait for $Scope to Really Apply Changes in Html

Wait for $Scope to Really Apply Changes in Html

I'm having a problem trying to detect when the $scope variable really affect the html. I need to access to the element after the $scope really apply the changes to the html, but the $scope.$watch is not doing the trick.

JS:

$scope.variable = "<p id='myElement'>Hello world!</p>";
console.log(jQuery('#myElement')[0]);

HTML:

<div ng-bind-html="varible | trustAsHtml"></div>

The problem is that, even if the $scope is applying the new content, the element still doesn't exist and jQuery returns undefined, so i need to wait untill the $scope really apply the changes to the html.

I know that a solution could be the $timeout but it's not really reliable, there is something that could help me?

1

1 Answer

Dunno why you need jQuery - there is probably an easier way with angular but there you go: angular has private method called $$postDigest, since all the DOM and model changes happens during $digest cycle it should do what you want, the other method would be to use $timeout, I've made working plunker for you

$scope.htmlvar = $sce.trustAsHtml('<strong>Test</strong>');

$timeout(function () {
  console.log('timeout', jQuery('strong').text())
}, 0, false) //false to not run another digest

$scope.$$postDigest(function () {
  console.log('postDigest', jQuery('strong').text())
})
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.