Scopes – AngularJS

AngularJS uses scopes to communicate between components – particularly between our javascript and our HTML. Scopes are the glue between our code and what the browser renders.

 

VIEW <——————> $scope <———————> VIEW MODEL

For example, say we want to show a welcome message to a user. We can use the $scope variable in our JavaScript code to make the user variable accessible to our view, the HTML:

1
2
3
4
5
6
angular.module(‘myApp’) // <– This is the getter function for a module previously defined

.run(function($rootScope) {

$rootScope.user = { email: ‘ari@fullstack.io’ } });

Now the HTML for our angular app can access the user variable in the view and bind it in our view.

1
<span>Welcome back {{ user.email }}</span>

The $rootScope is the top level scope for the rest of our application.

That means that anywhere in the view (i.e. all children elements under the DOM element with the ngApp directive) we can reference variables that are on the $rootScope object.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s