Before reading this article, I highly recommend reading the previous part of the series:
Here we are reading scope & expression.
$Scope Inheritance
If you define nested controllers then child controller will inherit the $scope of its parent controller.
It has two types:
$root Scope: An app can have only one $root scope which will be shared among all the components of an app. It is available in the entire application. It acts like a global variable.
Now you create your project.
- Open old visual studio project.
- Add new html file with name of inheritance.
Complete code
- <!DOCTYPE html>
- <html>
-
- <head>
- <title>Demo</title>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
- </script>
- <script>
- var app = angular.module('app', []);
- app.controller('AdminController', ['$scope', function ($scope)
- {
- $scope.Admin1name = 'Shiva';
- $scope.Name = 'Shukla ';
- }]);
- app.controller('SalsemanController', ['$scope', function ($scope)
- {
- $scope.salsemanname = 'Rakesh';
- $scope.Name = 'Kumar ';
- }]);
- app.controller('UserController', ['$scope', function ($scope)
- {
- $scope.Name = 'Rahul';
- }]);
- </script>
- </head>
-
- <body>
- <p>Controller Inheritance</p>
- <div ng-app="app" ng-controller="AdminController"> Admin1name : {{ Name }} {{ Admin1name }}
- <div ng-controller="SalsemanController"> Salsemanname : {{ Name }} {{ salsemanname }} {{ Admin1name }}
- <div ng-controller="UserController"> User name : {{ Name }} {{ salsemanname }} {{ Admin1name }} </div>
- </div>
- </div>
- </body>
-
- </html>
Output:
$Scope: $Scope is a JavaScript object that refers to the application model. It acts as glue between controller and view. $scope is passed as first argument to controller during its constructor definition.
Complete code
- <!DOCTYPE html>
- <html>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
- </script>
- <script>
- var app = angular.module('myApp', []);
- app.controller('myCtrl', function ($scope)
- {
- $scope.Adminname = "Shiva";
- });
- </script>
-
- <body>
- <div ng-app="myApp" ng-controller="myCtrl">
- <h1>{{Adminname}}</h1> </div>
- </body>
-
- </html>
Output Expression Expressions are used to bind application data to HTML. AngularJS expressions can be written inside double braces:
{{expression}}. It used for bindings to insert dynamic values into the html pages.
Complete code - <!DOCTYPE html>
- <html>
-
- <head>
- <title>Expression Demo</title>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
- </script>
- </head>
-
- <body>
- <div ng-app>
- <h2>Expressions in AngularJS</h2> The sum of 2 + 5 is = <strong>{{2 + 5}}</strong>. </div>
- </body>
-
- </html>
Output