Angular JS Scope

What is Angular JS scope?

The scope acts as a joining part between HTML and the Javascript. It contains the model data. It is an object with the available properties and methods. It is available for both views and controllers. In controllers the model data is accessed through $scope object.

Let us have a look at the example:

<div ng-app="my_app" ng-controller="my_ctrl">
<h1>{{message}}</h1>

</div>
<script>
var app = angular.module('my_app', []);
app.controller('my_ctrl', function($scope) {
    $scope.message = "hello!!good morning";
});
</script>

The property “message” was made in the controller, and it can be referred in the view by using the {{ }} brackets.

The $scope is passed as the first argument to controller during the constructor definition.

The $scope.message is the model which is used in the HTML page. The value has been set for the model which will be displayed in the application module whose controller is my_ctrl.

Inheritance in Scope

The scope is the controller specific where if we define the nested controller then the child controller will inherit the scope of its parent controller. Let us have a look at the example:

<div ng-app="my_app" ng-controller="my_ctrl">
<h1>{{message}}</h1>
</div>

<script>

var app = angular.module('my_app', []);
app.controller('my_ctrl', function($scope) {
    $scope.message = "hello!!good morning";
});

app.controller('ctrl',function($scope) {
$scope.message = "welcome to angularjs";
                });
</script>

In the above example the value has been set to model in my_ctrl and we have overridden the message in child controller ctrl where “message” is used within the module of controller ctrl, so the overridden message will be used.

$rootScope

Every application have the $rootScope and it is created in the html element which contains the ng-app directive. This scope is available in the whole application and if variable has the same name both in current scope and the root scope, then the application use the variable which is in the current scope. Let us have a look at the example:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="my_app">

<p>The rootScope's message is:</p>

<h1>{{message}}</h1>

<div ng-controller="my_ctrl">

<p>The scope of the controller message is :</p>
<h1>{{message}}</h1>

</div>

<p>The rootScope's message is:</p>
<h1>{{message}}</h1>

<script>
var app = angular.module('my_app', []);
app.run(function($rootScope) {
    $rootScope.message = 'hello!!good morning';
});
app.controller('my_ctrl', function($scope) {
    $scope.message = "welcome to angularjs";
});
</script>

In the above example the controller’s message variable does not override the rootscope message value.

By | 2017-07-22T17:11:28+00:00 March 6th, 2017|Angular|0 Comments

About the Author:

Leave A Comment