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 (32) -

  • 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.

Loading