Scope is a JavaScript object that connects Controller and View. Scope contains information of model, its properties and methods.
Characteristics of scope:
- Scope acts as a connection between Controller and View and available in both controller and view.
- Scope is the first argument passed in controller constructor.
- In MVC, scope can be act as ViewModel.
- Scope contains data and methods from Controller that executed in View
- We can define property and methods in scope.
- For each controller new scope is created.
- It contains data and functionality render in View.
- It provides an execution context for DOM and expression
- $rootScope is the top-most scope in DOM element and parent of all $scope.
- $scope can access their parent scope
- Only ng-controller and ng-repeat have their own scope.
How to Use the Scope?
When we create controllers in AngularJS, we pass $scope object as a parameter.
Example of Scope
<h2>Scope Example</h2>
@Styles.Render("~/Content/css")
<div ng-app="myApp" ng-controller="ctrl">
<input ng-model="name">
<h1>Hello {{name}}</h1>
</div>
@Scripts.Render("~/bundles/angularjquery")
<script>
var app = angular.module('myApp', []);
app.controller('ctrl', function ($scope) {
$scope.name = "World!";
});
</script>
OUTPUT :
Root Scope
$rootScope is the top-most scope in DOM element and parent of all $scope. All applications have a scope created on HTML element is called $rootScope. It contains ng-app directive. The rootScope can access from entire application. If same variable is present in both current scope and rootScope, then application use the current scope variable.
Example:
<h2>Root Scope Example</h2>
@Styles.Render("~/Content/css")
<div ng-app="myApp">
<div>
<strong>Root Scope :</strong> <br />
{{name}}
</div>
<div ng-controller="ctrl">
<strong>Current Scope : </strong> <br />
<div>{{name}}</div>
</div>
<div>
<strong> Root Scope :</strong> <br />
{{name}}
</div>
</div>
@Scripts.Render("~/bundles/angularjquery")
<script>
var app = angular.module('myApp', []);
app.run(function ($rootScope) {
$rootScope.name = 'root scope variable';
});
app.controller('ctrl', function ($scope) {
$scope.name = "currrent scope variable";
});
</script>
OUTPUT :
Hope, this sample will help you. Thanks
0 Comment(s)