Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for $scope to really apply changes in html

Tags:

angularjs

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?

like image 913
Gumma Mocciaro Avatar asked Jun 07 '26 07:06

Gumma Mocciaro


1 Answers

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())
})
like image 119
maurycy Avatar answered Jun 10 '26 18:06

maurycy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!