AngularJS Scopes and passing data controller to view

AngularJS Scopes and passing data controller to view

AngularJS Scopes and passing data controller to view:Scope is a special javascript object which plays the role of joining controller with the views. Thse scope is used for passing data or object of data from controller. Scope contains the model data. In controllers, model data is accessed via $scope object.

<script>
      var mainApp = angular.module("mainApp", []);

       mainApp.controller("PramodController", function($scope) {
         $scope.message = "Welcome Pramod controller";
         $scope.name = "Pramod";
      });
</script>
  • $scope is passed as first message argument to controller during its contructor defintion.
  • $scope.message and $scope.name are the models which are to be used in the HTML page.
  • We set values to models which will be reflected in the application module whose controller is PramodController.
  • We can define functions as well in $scope.

Example of scope in AngularJs

 <html>
        <head>
           <title>Angular Js $scope Example</title>
        </head>
        <body>
           <h2>Angular Js $scope Example</h2>
           <div ng-app="mainApp" ng-controller="ajayController">
              <p>{{message}} <br/> {{name}} </p>
              <div ng-controller="banwariController">
                 <p>{{message}} <br/> {{name}} </p>
              </div>
              <div ng-controller="PramodController">
                 <p>{{message}} <br/> {{name}} </p>
              </div>
           </div>
           <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
           <script>
              var mainApp = angular.module("mainApp", []);
        
              mainApp.controller("ajayController", function($scope) {
                 $scope.message = "Welcome ajay controller";
                 $scope.name = "Ajay";
              });
        
              mainApp.controller("banwariController", function($scope) {
                 $scope.message = "Welcome banwari controller"; 
                 $scope.name = "Banwari";  
              });
        
              mainApp.controller("PramodController", function($scope) {
                 $scope.message = "Welcome Pramod controller";
                 $scope.name = "Pramod";
              });
        
           </script>
        </body>
        </html>
Angularjsscopeexample

Angularjsscopeexample

Share Button

About admin

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Author: pramod kumar kumawat Mob: 9269727062
Free WordPress Themes - Download High-quality Templates