Scope of variables in AngularJS

November 25th, 2020

Scope of variables in angularJS
AngularJS is a structural framework for dynamic web apps. In angularJS we use HTML as the template language. Here we are discussing about the scope of variables in angularJS. Scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events. See the examples given below.

Example 1:


In the above example we can see two controllers “ctrl1” and “ctrl2”. In controller “ctrl1”, we can see a variable “name” and a value “Joe” assigned to it. Also we can see that, the variable “name” is used in controller “ctrl1” and controller “ctrl2”. On loading the page, we can see the following result.


In the above result, we can see null value for the second name. That means the scope of variable “name” is not available in the second controller. As the scope of the variable is local and it is available within the first controller.

If the requirement is to get the variable value within all controllers, we can give a root scope for that variable. This can be done as follows.

Example 2:


Here we are giving a root scope for the variable “name”, So the value will be available in the second controller “ctrl2” also. The result will be;


Hope, the post was helpful in enlightening of Angularjs variables and how it works.

Now meet and hire professional AngularJS developers at Cubet Techno Labs and get yours ideas converted to result-oriented applications within your budget.

Know More About This Topic from our Techies

Developing search friendly AngularJS applications
Angular14 Is Out with Tons of Great Features for Better Web App Development
React vs. Angular vs. Vue:
Angular web application development
Advantages and Disadvantages of Angular 5
typescrpit angular 2

Latest Post

Get a free quote