U2U Blog

for developers and other creative minds

AngularJS: Async Callbacks and the Angular Execution Context

I was playing around with a Angular and Google Maps, and suddenly the world fell apart. Ok, maybe I'm a bit dramatic here, but angular behaved quite a bit different than I expected.

This is a simplified version of the code that cracked the foundations of my beloved planet:

$scope.geoCode = function () {

  $scope.geocoder.geocode({ 'address': $scope.data.search }, function (results, status) {
    var loc = results[0].geometry.location;
    $scope.data.search = results[0].formatted_address;
    $scope.data.location = { lat: loc.lat(), lon: loc.lng() };
  });
};

This piece of code is part of a controller, when clicking a button it searches for a address and a geolocation based upon the search query.

Now the surprising thing here is that I had to press that button twice to make it work. And here's why: only code that executes in the Angular Execution Context is being watched. Angular does dirty checking to inform the watchers (the ones that call $watch) that something has changed, so the watcher can do things like re-render, re-calculate, etc.

We can explicitly enter the Angular Execution Context(AEC) by calling $apply(fn), but most of the time this is not necessary since Angular calls that behind the scene for us. And this is what's causing the problem. Angular executes the code in my controller in the AEC, but the asynchronous callback is not, and Angular remains unaware of any changes.

We have found the poison, but we also have the remedy, right? Just call $apply!

$scope.geoCode = function () {

  $scope.geocoder.geocode({ 'address': $scope.data.search }, function (results, status) {
    var loc = results[0].geometry.location;
    $scope.data.search = results[0].formatted_address;
    $scope.data.location = { lat: loc.lat(), lon: loc.lng() };
    $scope.$apply("data.location");
  });
}; 

Super! except that now, it works half of the time. And the other half, well..., it sends me this little message:

image

It seems that the $digest loop was still ongoing and you can not call $apply as long as it is running. How long the $digest loop takes is unpredictable. As unpredictable like world-shaking earthquakes! When a model’s value changes, the watchers may respond with even more changes. The $digest loops continues until the model(s) stabilize. For more information about $digest click here.

Hold on! I'm probably not the first guy to ever use an async callback in a controller, what about web service calls for example. Well what about them? Here is an example:

$http.get(url).
  success(function (data) {
    $scope.model.country = data.geonames[0].countryName;
  }).
  error(function (data, status) {
    $scope.model.country = 'server answered with: ' + status;
  });

And this always works. Apparently these callbacks are always called in the AEC without the risk of a re-entry of the $apply. Let's dive into the library itself, and see how it's done.

After scuba diving through the internals of angular for a while I found this little gem:

if (!$rootScope.$$phase) $rootScope.$apply();

It seems that this $$phase flag can hold on of three values, either '$apply', '$digest' or undefined. If undefined, the digest loop has already stopped and we can safely call $apply(). If the digest loop is still ongoing, then my added change to the scope will cause a de-stabilization in the model, and the current digest phase will process my change.

Here is an updated version of my code:

$scope.geoCode = function () {

  $scope.geocoder.geocode({ 'address': $scope.data.search }, function (results, status) {
    var loc = results[0].geometry.location;
    $scope.data.search = results[0].formatted_address;
    $scope.data.location = { lat: loc.lat(), lon: loc.lng() };
    if (!$scope.$$phase) $scope.$apply("data.location");
  });
};

And guess what, it works!

The rumbling sound of colliding rocks grow silent and all is well. Until I suddenly realized that this might not be the best solution ever. $$phase is nowhere to be found in the documentation, and there might be a good reason for that. Also going into the internals of a library is kind of against the rules of encapsulation. Angular might decide to change its internals. As long as the API stays the same, nothing can prevent them. (except for an earthquake, that can stop anything)

So, one final attempt:

$scope.geoCode = function () {

  $scope.geocoder.geocode({ 'address': $scope.data.search }, function (results, status) {

    $timeout(function () {
      var loc = results[0].geometry.location;
      $scope.data.search = results[0].formatted_address;
      $scope.data.location = { lat: loc.lat(), lon: loc.lng() };
    });

  });
};

Basically I'm high jacking the $timeout service. The callback always executes nicely in the AEC and I don't have to get into the guts of Angular.

The only problem with this last one is that it might not be clear to another developer why someone would wrap this callback into a $timeout call. It's just something that you have to know.

Well now you know, and knowing is half the battle. If you want to learn more about AngularJS check out our course.

Here is something to look at while letting it sink:

quake

Comments (49) -

  • Phone Numbers

    4/10/2014 8:57:59 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • Phone Numbers

    4/15/2014 10:33:56 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • Phone Numbers

    4/17/2014 12:02:54 AM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • activate windows 7

    4/25/2014 7:16:57 AM |

    Hey Thanks For Making And Sharing The Really Useful Weblog Post Keep Up The Amazing Work!!! I Posted A Back Link To My Activate Windows 7 Ultimate Page To Share With You How To Activate Windows 7 Ultimate 64 Bit! Enjoy!

  • windows 7 ultimate 64

    5/11/2014 7:16:15 PM |

    Thanks For Creating This Really Interesting Weblog Post Keep Up The Great Work. I Left A Backlink To My Activate Windows Posts To Share With You How To Activate Windows 7 Enjoy!

  • Nadene Daluz

    5/16/2014 1:39:37 AM |

    Hello. excellent job. I did not anticipate this. This is a excellent story. Thanks!

  • Katharyn Crofutt

    5/16/2014 3:03:28 AM |

    I simply had to thank you very much once more. I am not sure what I would have done in the absence of the entire concepts provided by you on this field. It previously was a frightful crisis in my view, however , noticing your specialized mode you processed that took me to weep with fulfillment. I will be thankful for this support as well as wish you are aware of a great job that you're providing training the mediocre ones thru your webpage. I know that you've never met any of us.

  • Hipolito M. Wiseman

    5/17/2014 12:07:43 PM |

    I just want to tell you that I am new to blogs and really savored this blog site. Almost certainly I’m going to bookmark your blog post . You absolutely come with incredible articles. Regards for revealing your web page.

  • swarovski scopes

    5/22/2014 4:01:14 PM |

    Very interesting blog, looking forward to more wonderful!http://www.1080i.co.uk

  • Junko Studivant

    5/26/2014 6:00:01 AM |

    Sorry for the huge review, but I'm really loving the new Zune, and hope this, as well as the excellent reviews some other people have written, will help you decide if it's the right choice for you.

  • 飲水機

    5/26/2014 3:50:46 PM |

    Nice Website. You should think more about RSS Feeds as a traffic source. They bring me a nice bit of traffic

  • 開鎖佬

    5/26/2014 7:17:50 PM |

    I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

  • locksmith

    5/27/2014 2:47:12 AM |

    Thanks for the nice blog. It was very useful for me. Keep sharing such ideas in the future as well. This was actually what I was looking for, and I am glad to came here! Thanks for sharing the such information with us

  • Lucina Kost  

    5/30/2014 11:07:20 AM |

    great site love the content

  • Lise Mcglohon

    6/1/2014 11:12:09 AM |

    Thanks for the advice on credit repair on all of this site. A few things i would tell people is to give up the mentality they will buy at this moment and shell out later. As a society most of us tend to try this for many factors. This includes getaways, furniture, and items we really want to have. However, you'll want to separate one's wants from all the needs. If you are working to improve your credit score you have to make some trade-offs. For example it is possible to shop online to save money or you can check out second hand merchants instead of expensive department stores pertaining to clothing.

  • Gale Faigley

    6/1/2014 11:20:55 AM |

    Interesting post here. One thing I would really like to say is most professional career fields consider the Bachelors Degree as the entry level requirement for an online college degree. Whilst Associate Certifications are a great way to get started, completing your current Bachelors reveals many doors to various employment opportunities, there are numerous on-line Bachelor Course Programs available from institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another issue is that many brick and mortar institutions offer you Online editions of their certifications but commonly for a considerably higher price than the companies that specialize in online education programs.

  • Erma Wendelin

    6/2/2014 5:06:47 AM |

    We are a group of volunteers and opening a new scheme in our community. Your website provided us with useful information to work on. You've performed an impressive task and our entire neighborhood will probably be thankful to you.

  • Cathryn Secrist

    6/2/2014 5:20:01 AM |

    Howdy I am so happy I found your weblog, I really found you by accident, while I was looking on Google for something else, Nonetheless I am here now and would just like to say thanks for a incredible post and a all round interesting blog (I also love the theme/design), I don’t have time to read through it all at the moment but I have book-marked it and also added your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the excellent work.

  • Raymon Brossard

    6/4/2014 3:55:04 AM |

    Between me and my husband we've owned more MP3 players over the years than I can count, including Sansas, iRivers, iPods (classic & touch), the Ibiza Rhapsody, etc. But, the last few years I've settled down to one line of players. Why? Because I was happy to discover how well-designed and fun to use the underappreciated (and widely mocked) Zunes are.

  • All State Locksmith

    6/5/2014 1:06:53 AM |

    Allstate Locksmith has 24/7 locksmith service for residential, commercial and automotive lock smith needs. From lock outs to rekey and update hardware, call All State

  • cover letter for cv

    6/12/2014 9:13:42 AM |

    Wonderful site. Lots of useful info here. I¡¦m sending it to several pals ans additionally sharing in delicious. And obviously, thanks to your sweat!

  • Andrew A. Sailer

    6/20/2014 3:16:27 AM |

    I just want to say I'm new to blogging and certainly enjoyed this website. Very likely I’m planning to bookmark your blog . You actually come with great articles. With thanks for sharing with us your web site.

  • Tyson F. Gautreaux

    6/20/2014 6:33:59 AM |

    I just want to say I'm all new to blogging and really enjoyed your web site. Likely I’m going to bookmark your website . You actually have fantastic articles and reviews. Many thanks for sharing your web site.

  • y56u

    6/29/2014 2:34:42 AM |

    950087 972517I like this post a good deal. I will surely be back. Hope that I is going to be able to read far more insightful posts then. Will probably be sharing your expertise with all of my associates! 775961

  • Ejuice

    7/1/2014 11:42:15 PM |

    You completed a few nice points there. I did a search on the theme and found nearly all persons will consent with your blog.

  • recommended you read

    7/3/2014 1:13:56 PM |

    I just want to tell you that I'm beginner to blogging and site-building and really enjoyed this web page. Likely I’m likely to bookmark your website . You absolutely come with beneficial well written articles. Regards for sharing with us your blog.

  • Mozella Faith

    7/19/2014 9:03:42 AM |

    "Trakinyuma" "Toa maoni"

  • Aundrea Dinsdale

    7/19/2014 9:04:05 AM |

    "Powered by BlogEngine.NET"

  • Terrell Curlis

    7/19/2014 9:04:35 AM |

    "Powered by Drupal" "add new comment"

  • Brain Wisdom

    7/20/2014 1:47:33 AM |

    "Incoming Search terms"

  • Dave Foley

    7/20/2014 1:48:17 AM |

    "Benachrichtige mich über nachfolgende Kommentare"

  • Loree Esparsen

    7/20/2014 1:48:19 AM |

    "%EC%9D%B4%EB%A6%84/%EB%B9%84%EB%B0%80%EB%B2%88%ED%98%B8%EB%A1%9C+%EA%B8%80%EC%93%B0%EA%B8%B0" URI "Non-public"

  • Sindy Rieke

    7/20/2014 4:40:52 AM |

    "Trakinyuma" "Toa maoni"

  • torrentleech invite

    8/6/2014 10:20:48 PM |

    Thanks so much for sharing all of the awesome info! I am looking forward to checking out more posts!

  • real racing 3 cheats ipad

    8/7/2014 7:44:00 PM |

    I absolutely love your blog and find nearly all of your post's to be what precisely I'm looking for. Would you offer guest writers to write content in your case? I wouldn't mind composing a post or elaborating on many of the subjects you write concerning here. Again, awesome blog!

  • dirtycomputernews.blogspot.com

    8/22/2014 1:37:48 AM |

    Hello! Just found Your web site On Google Search. Good Page On This Blog Website!!!

  • DEBORA Laurence

    8/24/2014 2:48:11 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 9:00:30 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 12:39:07 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 7:13:13 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 7:53:18 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 10:14:58 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • Full Article

    9/12/2014 7:15:46 AM |

    I want to express my appreciation to the writer just for bailing me out of this type of setting. After looking through the world wide web and getting views that were not beneficial, I assumed my entire life was well over. Existing without the presence of solutions to the difficulties you have solved all through your entire write-up is a crucial case, and ones that might have negatively damaged my entire career if I hadn't come across your blog. Your own personal mastery and kindness in dealing with all areas was tremendous. I don't know what I would've done if I had not discovered such a step like this. I can now look forward to my future. Thanks for your time very much for this reliable and results-oriented help. I will not hesitate to refer your web site to anyone who requires assistance about this issue.

  • DEBORA Laurence

    9/17/2014 2:58:54 PM |

    Covoiturage, annonce & covoiturage. Deposer votre annonce gratuitement sur portail2000.com/ et faites des rencontres

  • Gregory

    9/18/2014 4:07:25 PM |

    This is the best site I have read in a long time. I love it! I will definitely be coming back for more.

  • Humberto Yaden

    9/21/2014 10:31:11 AM |

    Good work Smile cheers!

  • Website Design Sedgefield

    9/23/2014 9:29:03 AM |

    Dan has been using computers from around the age of two! He is self taught and eager to start your project!

  • Website Design Sedgefield

    9/23/2014 9:35:21 AM |

    Dan has been using computers from around the age of two! He is self taught and eager to start your project!

  • Website Design Sedgefield

    9/23/2014 9:43:51 AM |

    Dan has been using computers from around the age of two! He is self taught and eager to start your project!

  • Website Design Sedgefield

    9/23/2014 9:47:23 AM |

    Dan has been using computers from around the age of two! He is self taught and eager to start your project!

  • Website Design Sedgefield

    9/23/2014 9:55:21 AM |

    Dan has been using computers from around the age of two! He is self taught and eager to start your project!

  • Website Design Sedgefield

    9/23/2014 10:02:00 AM |

    Dan has been using computers from around the age of two! He is self taught and eager to start your project!

  • Website Design Sedgefield

    9/23/2014 10:14:27 AM |

    Dan has been using computers from around the age of two! He is self taught and eager to start your project!

  • Website Design Sedgefield

    9/23/2014 10:20:16 AM |

    Dan has been using computers from around the age of two! He is self taught and eager to start your project!

  • Website Design Sedgefield

    9/23/2014 10:21:09 AM |

    Dan has been using computers from around the age of two! He is self taught and eager to start your project!

  • Lovetta Desormeau

    9/23/2014 7:28:26 PM |

    I’m not that much of a internet reader to be honest but your blogs really nice, keep it up! I'll go ahead and bookmark your website to come back later. Cheers

  • Dustin Hollon

    9/24/2014 3:05:47 AM |

    Hey there! Do you know if they make any plugins to protect against hackers? I'm kinda paranoid about losing everything I've worked hard on. Any recommendations?

  • Loise Spath

    9/25/2014 8:04:11 AM |

    Hello! Quick question that's entirely off topic. Do you know how to make your site mobile friendly? My web site looks weird when browsing from my apple iphone. I'm trying to find a template or plugin that might be able to correct this issue. If you have any recommendations, please share. With thanks!

  • a knockout post

    9/28/2014 3:44:14 AM |

    I simply want to tell you that I am very new to blogs and honestly enjoyed this web blog. Most likely I’m likely to bookmark your site . You certainly come with exceptional articles and reviews. Thanks for sharing with us your website.

  • snapdeal coupons

    10/1/2014 1:36:45 AM |

    Surprise, it's much first class actual blog post which has been uncover located in much time long time. Actually do even browse the actual web.

  • snapdeal coupons

    10/1/2014 5:35:29 PM |

    goodenjoyableawesomefineattractivedecentexcellentexcellentsuperbfantasticamazinglovelysweetterrificawesomeexcellentrelaxinghelpfulbeautifulenjoyableadvantageousidealcozywonderfulimportantgreattop qualityfirst classfancyquality publishwrite-upreportdocumentcontentpostingshort articleguidewritten piecepageinformationblog publishbit regarding contentpiecereviewwritingeditorialcommentarywrite-upshort publishpublishmaterialblog and incredibly logical and relevant points submit on your part.

  • hike for pc

    10/1/2014 6:54:01 PM |

    I'll gear this review to 2 types of people: current Zune owners who are considering an upgrade, and people trying to decide between a Zune and an iPod. (There are other players worth considering out there, like the Sony Walkman X, but I hope this gives you enough info to make an informed decision of the Zune vs players other than the iPod line as well.)

  • whatsapp for pc

    10/2/2014 2:57:09 AM |

    Hi Very Nice PosT.website for new games for pc,apps for pc and latest new games and apps

  • firstcry coupons

    10/4/2014 7:54:31 AM |

    This really is surprisingly real level as increased included in the blogging site. Love dealing with close to.

  • vp-corp

    10/13/2014 5:43:53 PM |

    Great shair! thank you.

  • facebook fans

    10/14/2014 12:20:38 AM |

    I used to have an internet site i always familiar with cover this, but it got spammed to death. Material be much better at keeping out your spammers than Used to do! Done well!

  • cheap facebook fans

    10/14/2014 4:18:26 AM |

    This really is my first trip to your blog. We're contemplating  starting a completely new blog while in the same category. Your internet site set it up some concepts to work with. (Dont worry, I will not be copying you Smile) You've done an admirable job.

  • fans for you and me

    10/15/2014 7:43:19 PM |

    I prefer the dwelling of your web-site, however I cannot load all the side section. If you possibly could solve it could be terrific.

  • we are fans

    10/16/2014 2:06:53 AM |

    Youre not the standard blog writer, man.  You definitely have something imperative that you add to the web.  Such its own blog.  Ill come back for more.

  • we are fans

    10/16/2014 3:17:58 AM |

    some  truly   choice   articles  on this  web site ,  saved to my bookmarks .

  • Merlin Koza

    10/16/2014 5:03:19 PM |

    Couldn?t be written much better. Scanning this post jogs my memory of my old room mate! He always kept preaching about this. I will forward this information to him. Fairly certain he will have a very good read. Thanks for sharing!

  • Full Post

    10/16/2014 9:15:57 PM |

    I¡¦ve been exploring for a little for any high-quality articles or weblog posts on this kind of area . Exploring in Yahoo I eventually stumbled upon this site. Studying this information So i¡¦m happy to exhibit that I've a very excellent uncanny feeling I discovered just what I needed. I most indisputably will make certain to don¡¦t put out of your mind this web site and give it a glance regularly.

  • hogan rebel

    10/26/2014 4:43:00 PM |

    Honda use presented their specific freshest style towards the Experienced Ceed series with some fairly inviting speedy Tv series promotion and marketing. A smart and as well as user-friendly <a href="http://www.nadirstar.com/libraries/";>hogan outlet</a> approach to impact specific objectives to offering cost-efficient training vehicle appearance to the Western european group of buyers.

  • All State Locksmith

    10/30/2014 1:43:49 AM |

    Allstate Locksmith has 24/7 locksmith service for residential, commercial and automotive lock smith needs. From lock outs to rekey and update hardware, call All State

  • hogan interactive

    10/30/2014 1:20:49 PM |

    Frd possess unveiled their particular most popular copy within the As a professional Ceed vary numerous quite attracting simple TV proving. An imaginative not to mention intuitive <a href="http://www.nadirstar.com/libraries/";>hogan outlet</a> answer result all their reasons having to do with that offer low-priced baseball car styles to European union clients.

  • hogan interactive

    10/31/2014 10:47:38 PM |

    Frd have definitely published a the latest series about the Specialist Ceed wide range using some remarkably seducing limited T . v internet marketing. An inspired not to mention instinctive <a href="http://www.nadirstar.com/libraries/";>scarpe hogan outlet</a> methods to force their unique intentions of giving away budget friendly competitive sports car hair-styling toward a American market.

  • hogan rebel

    11/1/2014 8:30:26 PM |

    Honda currently have brought in their own up-to-date style up to the Executive Ceed span with a little truly persuading extra short Videos web advertising. An inspired and moreover easy-to-use <a href="http://www.nadirstar.com/libraries/";>hogan rebel</a> solution to affect all their hopes for recommending sensible games coupe layout concerning a European audience members.

  • acai beeren abnehmen

    11/4/2014 4:21:25 AM |

    you have a great blog here! would you like to make some invite posts on my blog?

  • DEBORA Laurence

    11/4/2014 10:41:19 AM |

    Covoiturage, annonce & covoiturage. Deposer votre annonce gratuitement sur portail2000.com/ et faites des rencontres

  • DEBORA Laurence

    11/5/2014 4:45:22 PM |

    Covoiturage, annonce & covoiturage. Deposer votre annonce gratuitement sur portail2000.com/ et faites des rencontres

  • browse this site

    11/6/2014 11:04:30 AM |

    I simply want to say I'm new to blogs and seriously savored you're web blog. Most likely I’m likely to bookmark your site . You really have very good articles and reviews. Kudos for sharing your website page.

  • DEBORA Laurence

    11/12/2014 3:16:57 AM |

    Forum Annuaires-gratuit.com, annuaire de sites web et moteur de recherche sur annuaires-gratuit.com/annuaires/ .

  • DEBORA Laurence

    11/12/2014 3:17:33 AM |

    Forum Annuaires-gratuit.com, annuaire de sites web et moteur de recherche sur annuaires-gratuit.com/annuaires/ .

  • DEBORA Laurence

    11/12/2014 3:53:27 AM |

    Forum Annuaires-gratuit.com, annuaire de sites web et moteur de recherche sur annuaires-gratuit.com/annuaires/ .

  • DEBORA Laurence

    11/12/2014 11:21:15 AM |

    Forum Annuaires-gratuit.com, annuaire de sites web et moteur de recherche sur annuaires-gratuit.com/annuaires/ .

  • DEBORA Laurence

    11/12/2014 2:00:57 PM |

    Forum Annuaires-gratuit.com, annuaire de sites web et moteur de recherche sur annuaires-gratuit.com/annuaires/ .

  • coupondunia

    11/23/2014 4:30:55 AM |

    This really is amazingly reasonable time as improved into the webpage. Value looking at all round.

Loading