What are scope and scope inheritance in AngularJS ?
The $scope object used by views in AngularJS are organized into a hierarchy. There is a root scope, and the $rootScope can has one or more child scopes. Each controller has its own $scope (which is a child of the $rootScope), so whatever variables you create on $scope within controller, these variables are accessible by the view based on this controller.
For example - You have two controllers: ParentController and ChildController as given below:
- <!DOCTYPE html>
- <html>
- <head>
- <title>Angular Scope Inheritance</title>
- <script src="lib/angular.js"></script>
- <script>
- var app = angular.module('ScopeChain', []);
- app.controller("parentController", function ($scope) {
- $scope.managerName = 'Shailendra Chauhan';
- $scope.$parent.companyName = 'Dot Net Tricks'; //attached to $rootScope
- });
- app.controller("childController", function ($scope, $controller) {
- $scope.teamLeadName = 'Deepak Chauhan';
- });
- </script>
- </head>
- <body ng-app="ScopeChain">
- <div ng-controller="parentController ">
- <table style="border:2px solid #e37112">
- <caption>Parent Controller</caption>
- <tr>
- <td>Manager Name</td>
- <td></td>
- </tr>
- <tr>
- <td>Company Name</td>
- <td></td>
- </tr>
- <tr>
- <td>
- <table ng-controller="childController" style="border:2px solid #428bca">
- <caption>Child Controller</caption>
- <tr>
- <td>Team Lead Name</td>
- <td></td>
- </tr>
- <tr>
- <td>Reporting To</td>
- <td></td>
- </tr>
- <tr>
- <td>Company Name</td>
- <td></td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
- </div>
- </body>
- </html>
Angular Scope Inheritance
The contenders:
- The following create new scopes, and inherit prototypically: ng-repeat, ng-include, ng-switch, ng-view, ng-controller, directive with
scope: true
, directive withtransclude: true
. - The following creates a new scope which does not inherit prototypically: directive with
scope: { ... }
. This creates an "isolate" scope instead.
Note, by default, directives do not create new scope -- i.e., the default is
scope: false
.
ng-include
Suppose we have in our controller:
$scope.myPrimitive = 50;
$scope.myObject = {aNumber: 11};
And in our HTML:
<script type="text/ng-template" id="/tpl1.html">
<input ng-model="myPrimitive">
</script>
<div ng-include src="'/tpl1.html'"></div>
<script type="text/ng-template" id="/tpl2.html">
<input ng-model="myObject.aNumber">
</script>
<div ng-include src="'/tpl2.html'"></div>
0 comments:
Post a Comment