AngularJs Scope In Controller
scope in controller
AngularJS Controllers
We have now seen the relevance of modularization and how controllers can be added to Angular modules.
Let us now try to understand more about Angular controllers and their usage in the web page.
- Every controller receives $scope as a mandatory argument. $scope helps in binding the model between the view and the controller.
- The $scope instance is specific to where the controller is included in the view using the directive ng-controller.
- For every invocation of the controller using ng-controller, a new instance of the controller is created and a separate scope is attached to the DOM element having ng-controller.
Let us now invoke the same controller in two different html elements.
Demo
CODE/PROGRAM/EXAMPLE
<html ng-app="app">
<head>
<script src="lib/Angular/angular.js"></script>
<script src="js/controllers.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<div id="div1" ng-controller="userCtrl" style="border: 1px solid red">
<p><label for="username">Username:</label>
<input type="text" name="username" ng-model="username" id="username" >
<span id="displayUsername"> Your username is:<i>{{ username }}</i> </span></p>
<p><label for="mobile">Mobile:</label>
<input type="number" name="mobile" ng-model="mobile" id="mobile" >
<span id="displayMobile"> Your mobile number is:<i>{{ mobile }}</i> </span></p>
<p><label for="password">Password:</label>
<input type="password" id="password" ng-model="password" name="password" />
<span id="displayPassword"> Your entered the password: <i>{{password}}</i> </span></p>
</div>
<br>
<div id="div2" ng-controller="userCtrl" style="border: 1px solid blue">
<p><label for="mobile">Mobile:</label>
<input type="number" name="mobile" ng-model="mobile" id="mobile" >
<span id="displayMobile"> Your mobile number is:<i>{{ mobile }}</i> </span></p>
</div>
</body>
</html>