×

Html & Html5

The World's best Software Development Study Portal

Angular JS Scope


  • Scope is a JavaScript object that refers to the application model.

  • It acts as a context for evaluating Angular expressions.

  • Basically,it acts as the glue between a controller and a view.

  • The $scope in an AngularJS is a built-in object, which contains application data and methods.

  • You can create properties to a $scope object inside a controller function and assign a value or function to it.

  • Scopes are hierarchical in nature and follow the DOM structure of your AngularJs app.

  • In the view, you do not use the prefix $scope, you just refer to a property name.







  • Keypoints:

  • The Scope is an object that is specified as a binding part between the HTML (view) and the JavaScript (controller).

  • It plays a role of joining controller with the views.

  • It is available for both the view and the controller.

  • The scope is an object with the available properties and methods.

  • To make a controller in AngularJS, you have to pass the $scope object as an argument.

  • When adding properties to the $scope object in the controller, the view (HTML) gets access to these properties.

  • In the view, you do not use the prefix $scope, you just refer to a property name.






  • For Example:

         <div ng-app="myApp" ng-controller="myCtrl">
    
         <input ng-model="name">
    
         <h1>welcomes you {{name}}</h1>
    
         </div>
    
         <script>
         var app = angular.module('myApp', []);
         app.controller('myCtrl', function($scope) {
         $scope.name = "IT training institute";
         });
         </script>
    
    Output

    Welcomes You {{name}}



    Note: The ng-model directive is used for two-way data binding. It transfers the data from controller to view and vice-versa. An expression and ng-bind directive transfers data from controller to view but not vice-versa.


    Root Scopes:


    All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive.

    The rootScope is available in the entire application.

    If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.



    Lets see an another Example:

    <body ng-app="myApp">

    <p>The rootScope's favorite color:</p>
    <h1>{{color}}</h1>

    <div ng-controller="myCtrl">
      <p>The scope of the controller's favorite color:</p>
      <h1>{{color}}</h1>
    </div>

    <p>The rootScope's favorite color is still:</p>
    <h1>{{color}}</h1>

    <script>

    var app = angular.module('myApp', []);
    app.run(function($rootScope) {
      $rootScope.color = 'blue';
    });
    app.controller('myCtrl', function($scope) {
      $scope.color = "red";
    });
    </script>
    </body>