AngularJS, the Digest Loop, Directives and jQuery

Posted by Peter Kellner on October 30, 2014 · 1 min read

I've been struggling with understanding when and how to use jQuery inside an AngularJS directive and have the data binding work as expected.  I've got a good example I put together that shows how to do this as well as shows when you need to use the scope.$apply().  As a developer who spends a lot of time working with Microsoft technology, it's become very clear to me that I need to know a lot about AngularJS. AngularJS is a technology that Microsoft (Visual Studio) is pushing as a defacto standard and I'm sure they will have a lot of offerings that either use Angular or are inspired by it.

You can see from the below example that in the directive, I am using AngularJS.  Because our DOM is being modified outside of what AngularJS can see, it does not have a watch assigned to it and therefore in the AngularJS digest loop, the scope.cntjQuery does not get updated.  As we know, the $scope contains the "truth" of this application but if the digest loop is not run then the truth never makes it to the browser.  Calling scope.$apply() causes the digest loop to be run.

I've also made a short video showing and talking about this particular example.  HTH's!

(inspired by the post http://angular-tips.com/blog/2013/08/watch-how-the-apply-runs-a-digest/)