background preloader

AngularJS and scope.$apply — Jim Hoskins

AngularJS and scope.$apply — Jim Hoskins
If you’ve written a non-trivial amount of code in AngularJS, you may have come across the $scope.$apply() method. On the surface, it may seem like just a method you call to get your bindings to update. But why does it exist? And when do you need to use it? To really understand when to use $apply, it’s good to know exactly why we need to use it, so let’s dive in! JavaScript is Turn Based The JavaScript code we write doesn’t all run in one go, instead it executes in turns. Instead, whenever there is a task that takes some amount of time, such as an Ajax request, waiting for a click event, or setting a timeout, we set up a callback function and finish our current turn. Let’s look at an example JavaScript file: var button = document.getElementById('clickMe'); function buttonClicked () { alert('the button was clicked'); } button.addEventListener('click', buttonClicked); function timerComplete () { alert('timer complete'); } setTimeout(timerComplete, 2000); How do we update bindings? $scope. Related: