Easy Tutorial
❮ Ng Ng Selected Ng Ng Submit ❯

AngularJS Scope(Scope)

Scope is the binding part between the HTML (view) and the JavaScript (controller).

Scope is an object with available methods and properties.

Scope can be applied to both the view and the controller.


How to Use Scope

When you create a controller in AngularJS, you can pass the $scope object as a parameter:

AngularJS Example

Properties in the controller correspond to properties in the view:

When you add the $scope object in the controller, the view (HTML) can access these properties.

In the view, you do not need to add the $scope prefix; just add the property name, such as: {{carname}}.


Scope Overview

An AngularJS application consists of:

Scope is the model.

Scope is a JavaScript object with properties and methods that can be used in both the view and the controller.

AngularJS Example

If you modify the view, the model and controller will also be updated accordingly:

<div ng-app="myApp" ng-controller="myCtrl">
    <input ng-model="name">
    <h1>{{greeting}}</h1>
    <button ng-click='sayHello()'>Click Me</button>    
</div>

<script>var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name = "tutorialpro";
    $scope.sayHello = function() {
        $scope.greeting = 'Hello ' + $scope.name + '!';
    };
});</script>

Scope Scope

It is important to understand the scope you are currently working with.

In the above two examples, there is only one scope, so it is relatively simple to handle, but in large projects, there are multiple scopes in the HTML DOM, and you need to know which scope you are working with.

AngularJS Example

When we use the ng-repeat directive, each repeated item accesses the current repeated object:

Each <li> element can access the current repeated object, which is a string, represented by the variable x.


Root Scope

All applications have a $rootScope that can be applied to all HTML elements included in the ng-app directive.

$rootScope can be used throughout the application. It serves as a bridge between the scopes in various controllers. Values defined with rootscope can be used in all controllers.

AngularJS Example

When creating a controller, pass $rootScope as a parameter to use it in the application:

❮ Ng Ng Selected Ng Ng Submit ❯