Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMatthew Huntley
33,883 PointsAngular Basics: Question following "Using Services To Save and Delete Data" Video (RE: deleteTodo)
I'm currently taking the Angular Basics course and I've a question following the "Using Services To Save and Delete Data" video.
When we use the "ng-click" directive to called the "deleteTodo(todo)" method, I understand that we're splicing the todos array that's currently in scope, but at which point after this deleteTodo action takes place is the DOM "re-reading/re-evaluating", if you will, the now-shortened todos array, thus re-populating our div accordingly?
It would seem to me, upon first glance, that after calling "deleteTodo(todo)", the "ng-repeat" directive would have to run again. Is this the case? If so, when does this happen and are we explicitly telling it to or does Angular inherently detect that since the scope has changed, it should/does update the DOM automatically?
Thanks so much.
2 Answers
James Churchill
Treehouse TeacherMatthew,
Great questions! And nice job thinking about the details :)
So, the good news is that you typically don't have to tell AngularJS when the DOM needs to be updated, provided that you're writing code that stays inside of the AngularJS "world". For instance, when you need to make a call to an API, you're using AngularJS's $http
service instead of jQuery's $.ajax()
method.
The bad news is that understanding how that process works, can be a steep learning curve. Here's a quick overview.
When using the ngClick
directive, AngularJS calls the associated code (typically a function on your controller) within a call to the $scope.$apply()
method. The $apply()
method then calls the $scope.$digest()
method, which is responsible for calling all of the watchers, who then in turn are responsible for updating the DOM.
Easy, right?
It's difficult to give this process a proper explanation without writing a much longer response. Luckily, there are numerous articles and blog posts that cover how the scope $apply()
and $digest()
methods work. Here's an article from SitePoint:
https://www.sitepoint.com/understanding-angulars-apply-digest/
Hopefully this helps a bit. Don't hesitate to let me know if you have any follow up questions.
Thanks, James
Matthew Huntley
33,883 PointsThank you very much for the thorough summary, James; this helps clarify things a great deal.