TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: AngularJS Scope and Usage with Examples
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
AngularJSLinux Tutorials

AngularJS Scope and Usage with Examples

Last updated: Jan 15, 2024 12:32 am
By Meenakshi Agarwal
Share
8 Min Read
AngularJS Scope, Usage & Examples
SHARE

AngularJS scope is one of the core concepts of the Angular framework. And, it plays a vital role in defining the workflows of an AngularJS application.

Contents
How to Use the AngularJS Scope?Sample Code.Understanding the Scope.Sample Code.Know Your Scope.Sample Code.Output.Sample Code.Output.Scope Inheritance.Sample Code.Sample Code.Output.

In this post, we’ve tried to decipher this concept by elaborating its definition, usage, and examples. After reading, you’ll find it easy to use in your projects.

If you like to quickly brush up on Angular concepts, then do go through the below post once.

Must Read: 100+ AngularJS Interview Questions

AngularJS Scope

AngularJS Scope, Usage & Examples

The Scope is a special javascript object, that plays the role of joining the Controller with the View. It contains the Model data. A Controller can access this Model data using <$scope> object. It transfers the data from the Controller to the View and vice-versa. In other words, the Controller initializes the data for the View by making changes to the <$scope>.

How to Use the AngularJS Scope?

Let’s see the code of a Controller that is using a Scope object.

Sample Code.

<div ng-app="myApp" ng-controller="sampleCtrl">
<h1>{{Subject}}</h1>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('sampleCtrl', function($scope) {
$scope.subject = "Maths";
$scope.marks = " 75%";
});
</script>

Following are the important concepts that we should understand from the above code sample.

  • AngularJS passes <$scope> as the first argument to the Controller while defining its constructor.
  • <$scope.subject> and <$scope.marks> are the Models to be used in the HTML page.
  • We have set values for these Models, which are reflected in the application module. <sampleCtrl> is the Controller for this application.
  • The View (HTML) gets access to the properties that we attach to the <$scope> object of the Controller. If we make any modifications in the View, this, in turn, changes the Controller. It brings a change in the values of the properties or methods belonging to <$scope> object.
  • In the view, we do not use the prefix <$scope>. Instead, we refer to a property by its name as {{name}}.
  • We can also define functions in <$scope>.

Understanding the Scope.

If we assume that an AngularJS application is made up of

  • View, which is its HTML code.
  • Model, which is the data available for the current view and,
  • Controller, which is the JavaScript function that prepares, modifies, deletes, and controls the data.
  • Then, we can say that Scope is part of the Model.

To summarize, a Scope is a JavaScript object containing properties and methods, which are available to both the View and the Controller.

If we make any change in the View, the Model and the Controller get updated automatically.

Sample Code.

<div ng-app="myApp" ng-controller="sampleCtrl">

<input ng-model="name">

<h1>My name is {{name}}</h1>

</div>

<script>
var app = angular.module('myApp', []);

app.controller('sampleCtrl', function($scope) {
 $scope.name = "Ram Agarwal";
});
</script>

Know Your Scope.

In the above example, we have defined only one Scope, so determining the Scope is easy. However, HTML DOM of large applications may contain sections, that can access only specific Scope objects.

However, at any time of the code development process, we should know about the Scope object, that we are handling.

Let’s see the following example having two Scopes, Controllers, and roots.

Sample Code.

app.controller('WelcomeCtrl', function($scope) {
 $scope.message = 'Welcome Viewers !!';
});

app.controller('ErrorCtrl', function($scope) {
 $scope.message = 'Oops, there is some error, please Retry.';
});

<div ng-controller="WelcomeCtrl">
 <input ng-model="message">
 <span>{{message}}</span>
</div>
<div ng-controller="ErrorCtrl">
 <input ng-model="message">
 <span>{{message}}</span>
</div>

Output.

Welcome Viewers !!
Oops, there is some error, please Retry.

Even though both inputs bind to message property, they are completely independent. The reason being their association with different Scopes. Till now we have been talking about Scope, but are we aware of its creation?

Scope Creation: <$rootScope>

When we start an application, AngularJS creates the initial Scope and denotes it as <$rootScope>. All the other <$scope> objects are child objects. The properties and methods attached to <$rootScope> become available to all the Controllers. The following example demonstrates the use of <$rootScope> and <$scope> objects.

Sample Code.

<!DOCTYPE html>
<html>
<head>
 <title>AngualrJS Controller</title>
 <script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myApp">
 <div ng-controller="parentCtrl">
 Controller Name: {{controllerName}} <br />
 Message: {{message}} <br />
 <div style="margin:10px 0 10px 20px;" ng-controller="childCtrl">
 Controller Name: {{controllerName}} <br />
 Message: {{message}} <br />
 </div>
 </div>
 <div ng-controller="siblingCtrl">
 Controller Name: {{controllerName}} <br />
 Message: {{message}} <br />
 </div>
 <script>
 var ngApp = angular.module('myApp', []);

ngApp.controller('parentCtrl', function ($scope, $rootScope) {
 $scope.controllerName = "parentCtrl";
 $rootScope.message = "Welcome Viewers !!";
 });

ngApp.controller('childCtrl', function ($scope) {
 $scope.controllerName = "childCtrl";
 });

ngApp.controller('siblingCtrl', function ($scope) {
 });
 </script>
</body>
</html>

Output.

Following is the Output for the above code snippet.

Controller Name: parentCtrl
Message: Welcome Viewers !!
Controller Name: childCtrl
Message: Welcome Viewers !!
Controller Name:
Message: Welcome Viewers !!

As per the above example, each Controller has a separate scope created for it. Properties that get added in <$rootScope> are available to all the Controllers.

Scope Inheritance.

The Scope is bound to a Controller. If we define nested Controllers, then the child Controller will inherit the scope of its parent. Let’s take a sample code.

Sample Code.

<script>
 var mainApp = angular.module("mainApp", []);

 mainApp.controller("subjectCtrl", function($scope) {
 $scope.message = "In subject controller";
 $scope.type = "Subject";
 });

 mainApp.controller("englishCtrl", function($scope) {
 $scope.message = "In English Controller";
 });
 </script>

The following are the important points to be considered in the above code.

  • We have set the values of Models in <subjectCtrl>.
  • We have overridden the message property in the child Controller, <englishCtrl>. When we use the <message> property in <englishCtrl>, it prints the overridden message.

Here is the complete code for the code sample discussed above.

Sample Code.

<html>
 <head>
 <title>Angular JS Forms</title>
 </head>
 <body>
 <h2>AngularJS Sample Application</h2>

 <div ng-app = "mainApp" ng-controller = "subjectCtrl">
 <p>{{message}} <br/> {{type}} </p>

 <div ng-controller = "englishCtrl">
 <p>{{message}} <br/> {{type}} </p>
 </div>

 <div ng-controller = "mathsCtrl">
 <p>{{message}} <br/> {{type}} </p>
 </div>

 </div>

 <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>

 <script>
 var mainApp = angular.module("mainApp", []);

 mainApp.controller("subjectCtrl", function($scope) {
 $scope.message = "In Subject Controller";
 $scope.type = "Subject";
 });

 mainApp.controller("englishCtrl", function($scope) {
 $scope.message = "In English Controller";
 });

 mainApp.controller("mathsCtrl", function($scope) {
 $scope.message = "In Maths Controller";
 $scope.type = "Maths";
 });

 </script>
 </body>
 </html>

Output.

Name it as <textAngularJS.htm>. Open it in a web browser. The following output gets printed.

AngularJS Sample Application

In Subject Controller
Subject

In English Controller
Subject

In Maths Controller
Maths

If you liked this post on “AngularJS Scope“, then don’t mind sharing it further. Also, follow us on our social media accounts to receive more free learning material.

You Might Also Like

Basic Linux Commands for Beginners With Examples

How to Use Bash to Replace Character in String

AngularJS Tutorial – History, Present, and Key Terms

Simple Bash Scripting Tutorial for Beginners

20 Bash Script Code Challenges for Beginners with Their Solutions

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Setup AngularJS Development Environment Setup AngularJS for Development
Next Article AngularJS APIs, their Usage & Application with Examples Learn to Use AngularJS APIs with Examples

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x
x