Gumma Mocciaro
Gumma Mocciaro

Reputation: 1215

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?

Upvotes: 2

Views: 7008

Answers (1)

maurycy
maurycy

Reputation: 8465

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

http://plnkr.co/edit/oZ2xfoUQxcOzNw7eXCmT?p=preview

$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())
})

Upvotes: 9

Related Questions