0 votes
in Angular by
What is $scope in Angular?

1 Answer

0 votes
by

$scope is an object instance of a controller. $scope object instance gets created when ng-controller directive is encountered.

For example, in the below code snippet, we have two controllers - Function1 and Function2. In both the controllers, we have a ControllerName variable.

HTML

function Function1($scope)
{
$scope.ControllerName = "Function1";
}
function Function2($scope)
{
$scope.ControllerName = "Function2";
}

Now to attach the above controllers to HTML UI, we need to use ng-controller directive. For instance, you can see in the below code snippet how ng-controller directive attaches function1 with div1 tag and function2 with div2 tag.

HTML

<div id="div1" ng-controller="Function1">
Instance of {{ControllerName}} created
</div>
<div id="div2" ng-controller="Function2">
Instance of {{ControllerName}} created
</div>

So this is what happens internally. Once the HTML DOM is created, Angular parser starts running on the DOM and following are the sequence of events:

  • The parser first finds ng-controller directive which is pointing to Function1. He creates a new instance of $scope object and connects to the div1 UI.
  • The parser then starts moving ahead and encounters one more ng-controller directive which is pointing to Function2. He creates a new instance of $scope object and connects to the div2 UI.

Image 4

Now once the instances are created, below is a graphical representation of the same. So the DIV1 HTML UI is binded with function1 $scope instance and the DIV2 HTML UI is binded with function2 $scope instance. In other words, now anything changes in the $scope object, the UI will be updated and any change in the UI will update the respective $scope object.

Image 5

...