Angularjs scope multiple tutorial

Angularjs multiple scope:

In case of multiple controllers AngularJS framework creates and pass a different $scope object to each controller so that data and methods of one controller not be accessed in another controller.

Example Explanation:

First include the AngularJS library in the application. The ng-app directive initializes the application. The ng-model directive binds (two way binding) the state of the input text to the message variable. The ng-bind directive also binds the state of the input text to the message variable but using one way binding i.e. transfers data from controller to view but not vice-versa. The ng-controller directive defines the controller. We defined two controllers here and set their properties using $scope object. When execute the program both controllers show their respective data.

Example:

<!DOCTYPE html>
<html>
<head>
  <script src="
   https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js">
  </script>
</head>
<body ng-app="testApp">
<h1>AngularJS Scope Multiple Controllers.</h1>
    <div ng-controller="jaiController">
      	Controller Name: {{controllerName}}<br/>
        Message: {{message}}<br/>
        <span ng-bind="message"></span> <br/>
        <input type="text" ng-model="message"/> 
    </div>
  	<div ng-controller="vivekController">
      	Controller Name: {{controllerName}}<br/>
        Message: {{message}}<br/>
        <span ng-bind="message"></span> <br/>
        <input type="text" ng-model="message"/> 
    </div>
    <script>
        var ngApp = angular.module('testApp', []);
 
        ngApp.controller('jaiController', function ($scope) {
          	$scope.controllerName = "jaiController"; 
            $scope.message = "Hello Jai!";        
        });
 
       ngApp.controller('vivekController', function ($scope) {
         	$scope.controllerName = "vivekController";
            $scope.message = "Hello Vivek!";        
        });
    </script>
</body>
</html>

Try it:

JS Bin on jsbin.com  

Please follow and like us:
Content Protection by DMCA.com