What is $scope in AngularJS?

 $scope in AngularJS is a built-in object which basically binds the "controller" and the "view". One can define member variables in the scope within the controller which can then be accessed by the view.

Consider example below:


angular.module('app',[]).controller('HelloWorldCntrl'
function($scope)
{
$scope.message = "Hello World"
});

Code Explanation:
The name of the module is "app"
The name of the controller is "HelloWorldCntrl"
Scope object is the main object which is used to pass information from the controller to the view.
Member variable added to scope object

Setting up or adding Behavior:
In order to react to events or execute some sort of computation/processing in the View, we must provide behavior to the scope.
Behaviors are added to scope objects to respond to specific events that may be triggered by the View. Once the behavior is defined in the controller, it can be accessed by the view.
Let's look at an example of how we can achieve this.

<!DOCTYPE html>  

<html lang="en">  

<head>  

  <meta chrset="UTF 8">

    <title>ViASTUDY</title>     

</head>  

<body ng-app="DemoApp">

<h1> ViASTUDY Global Event</h1>

<script src="https://code.angularjs.org/1.6.9/angular.js"></script>

<div ng-controller="DemoController">

          {{fullName("ViASTUDY","Community")}}

</div>

<script type="text/javascript">  

          var app = angular.module("DemoApp", []);

          app.controller("DemoController", function($scope) {    $scope.fullName=function(firstName,lastname){

                   return firstName + lastname;

                 }

          } );

</script> 

</body>  

</html>


Output:

ViASTUDY Global Event

ViASTUDY

Post a Comment

0 Comments