Monday, 25 May 2015

Use of $scope

Scope is a special JavaScript object which plays the role of joining controller with the views. Scope contains the model data. In controllers, model data is accessed via $scope object.


main.html:-
<html>
<head>
<title>Angular JS Forms</title>
</head>
<body>
<h2>AngularJS Scope Application</h2>
<div ng-app="mainApp" ng-controller="shapeController">
<p>{{message}} <br/> {{type}} </p>
<div ng-controller="circleController">
<p>{{message}} <br/> {{type}} </p>
</div>
<div ng-controller="squareController">
<p>{{message}} <br/> {{type}} </p>
</div>
</div>
<script src="angular.min.js"></script>
<script src="app.js"></script>
<script src="controller.js"></script>
</body>
</html>


app.js:-
var mainApp = angular.module("mainApp", []);


controller.js:-
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
mainApp.controller("circleController", function($scope) {
$scope.message = "In circle controller";
});
mainApp.controller("squareController", function($scope) {
$scope.message = "In square controller";
$scope.type = "Square";
});



Screenshot:





Explanation:-

Here, "$scope" is passed as first argument to controller during its constructor definition.

"$scope.message" and "$scope.type" are the models which are to be used in the HTML page. I have set values to models which will be reflected in the application module whose controller is "shapeController"I can define functions as well in $scope.


The feature of scope - Scope are controllers specific. If we defines nested controllers then child controller will inherit the scope of its parent controller.

No comments:

Post a Comment