A couple of things about the $scope in AngularJS

The idea of scope, or rather $scope, always produces conflicting feelings when I work with AngularJS . It is a very clear concept but at the same time it has an abstract touch that sometimes seems to slip between the neurons, so it seemed a good idea to spend some time writing (to myself) this mental note for the next day that I face the köan that this idea means to me

What is the scope and what is it for?

The scope is the glue between the view and the controller. It is that object that carries with it the methods and properties that we can apply in the view and / or in the controller.


¿How does the scope works?

The idea sounds great but everything starts to get complicated when you roll up your sleeves and start digging into code so I’ll try to explain it with an example.

Let’s start with the view. A simple html but with a little dressing:


Inside the body tag we can find two nested divs with it’s angular directives. With the first one, ng-app, we define which module is “responsibly” of this element of the DOM and in the nested one (or in the same) we add the ng-controller directive. In this case counterController will be the controller in charge of this div and this is the way we can define the scope of the view.

vemos tenemos dos divs cada uno con su directiva de angular. Con ng-app definimos que modulo es “responsable” de este elemento del DOM y en un elemento anidado (o en el mismo) añadimos la directiva ng-controller. En este caso counterController será el controlador responsable de ese div y así definimos el scope en la vista. Let’s say that all that remains inside the element labeled with the ng-controller directive will be the scope for that controller.


And here is our module and our controller. The controller must always receive, at least, $scope. Here I must precede with $scope. all the properties and functions that I want to be accessible from the view. For example, the counter variable that is in the view. In the controller is preceded by $scope. same as the startCounter method.

In contrast, the timer variable or the updateCounter function are only used inside the controller and therefore it is not necessary to add any type of prefix outside of the JavaScript standars.