Unit 3-AngularJS Modules, Controller, View and Scope

unit 3 notes

3.1 Angular Modules

  • One of the most important feature of AngularJS is it supports modular approach. A Module is nothing but container for different parts of your app - controllers, services, filters, directives, etc. which is used to specify how application should be bootstrapped.
  • Module is an important part of AngularJS dependency injection system. It means we can say it is a container for the application controllers.
  • Module acts like a main () method in other application. AngularJS module is used to define functionalities or to add controllers, filters, directives etc. to the AngularJS application.
  • Module is easy to reuse in different applications.

Features of modules:

  • Separating business logic.
  • Using modular approach, declarative process is easier to understand.
  • Module is useful for packaging the code in reusable modules.
  • No order for loading modules.
  • It is easily maintainable, testable component.

Types of AngularJS Modules:

There are two types of AngularJS modules:

  • Application Modules
  • Controller Modules
  1. Application Modules in AngularJS
    • Using the function "angular.module" we can create an application module in angular.
    • To create Angular Modules, application modules consider as global space, retrieving angular Js modules and registering angular modules.
    • All the modules use for an application have to register using this mechanism whether it is angular core or any third party module.
    • <div ng-app="demo">
      </div>
      <script>var app = angular.module("demo",[ ]);</script>
    • Here in the above code "demo" parameter that is used to refer an HTML element (controls) in which the application will run. angular.module () creates an application module in which two parameters passes.
    • The first parameter is the module name that should be the same as specified by an ng-app directive.
    • The second parameter is an array of some other dependent modules. Since there is no dependency, therefore, we are passing an empty array. A module definition without its second parameter (module without []), implies that we are using an existing module rather than creating a new module. We are retrieving from the existing module only.
    • Using module API we can create services, factories and providers too.
    • The Syntax for creating service in a module:
      module.service( 'Name of service', function );
    • A Syntax for creating a factory in a module.
      module.factory( 'Name of Factory', function );
    • The Syntax for creating a provider in a module.
      module.provider( 'providerName', function );

  2. Controller Modules in AngularJS
  3. The AngularJS modules use to define a controller in an application. In the controller module, you have to add a controller in our application and that controller refers to the ng-controller directive.

    <html>
    <script src="angular.min.js"></script>
    <body>
    <div ng-app="App" ng-controller="myCtrl">
    {{ fName + " " + lName }}
    </div>
    <script>
    var a = angular.module("App", []);
    a.controller("myCtrl", function($scope) {
    $scope.fName = "Angular";
    $scope.lName = "JS framework";
    });
    </script>
    </body>
    </html>

3.2 Angular Controller

  • In every AngularJS application the controller is heart of the application.
  • It controls the flow of data from the model part to the view part.
  • From the view part, data is taken as an input by the controller then it process the data and sends back to the view part that is being displayed to the user.
  • It is defined using ng-controller directive
  • Controller is javascript object that contains functions properties.
  • Syntax:
    variablename.controller("string".function($scope))

  • Example
  • <html>
    <script src="angular.min.js"></script>
    <body>
    <div ng-app="myApp" ng-controller="myCtrl">
    First Name: <input type="text" ng-model="firstName">
    Last Name: <input type="text" ng-model="lastName">
    Full Name: {{firstName + " " + lastName}}
    </div>
    <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
    $scope.firstName = "ABC";
    $scope.lastName = "XYZ";
    });
    </script>
    </body>
    </html>
  • Defining Controller in AngularJS
    • By Application Module
    • <html>
      <script src="angular.min.js"></script>
      <body>
      <div ng-app="myApp" ng-controller="myCtrl">
      {{message}}
      </div>
      <script>
      var app = angular.module('myApp', []);
      app.controller('myCtrl', function($scope) {
      $scope.message = "Good Morning";
      });
      </script>
      </body>
      </html>
    • By Javasript Function
    • <html>
      <script src="angular.min.js"></script>
      <body>
      <div ng-app="myApp" ng-controller="mail">
      Enter name of the product:<input type=”text” ng-model="name"/>
      <button ng-click="add()">ADD</button>
      <h2>Contacts</h2>
      <ul><li ng-repeat="product in prroducts"> {{product}} </li></ul>
      </div>
      <script type="text/javascript">
      function mail ($scope)
      { $scope.products=["pen","book"];
      $scope.add=function()
      { $scope.products.push($scope.name);
      $scope.newcontact="";
      }
      }
      </script>
      </body>
      </html>
    • Nested Controller
    • <html>
      <head>
      <script src="angular.min.js"></script>
      </head>
      <body ng-app="myNgApp">
      <div ng-controller="parentController">Message: {{message1}}
      <div ng-controller="childController">
      Parent Message: {{message1}} </br>
      Child Message: {{message2}}
      </div>
      Child Message: {{message2}}
      </div>
      <script>
      var ngApp = angular.module('myNgApp', []);
      ngApp.controller('parentController', function ($scope) {
      $scope.message1 = "This is parentController";
      });
      ngApp.controller('childController', function ($scope) {
      $scope.message2 = "This is childController";
      });
      </script>
      </body>
      </html>

3.3 Angular View

  • A view is anything that a user can see that simple HTML page.
  • View is responsible to display all data to user. It show data in particular format which is easily understand by a user.
  • It will be triggered by the controller. The most important thing is that AngularJS supports partial view which help to creation of single page application.

3.4 Scope hierarchy

  • The Scope in AngularJS is the binding part between HTML (view) and JavaScript (controller) and it is a built-in object.
  • It contains application data and objects.
  • It is available for both the view and the controller.
  • It is an object with available properties and methods.
  • There are two types of scopes in Angular JS.
    • $Scope
    • $rootScope

Why AngularJS Scope is used?

To define member variables, AngularJS scope is used within a controller. It can contain variables that are the application data and methods.

Syntax-
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController", function($scope) {
//access member variable
$scope.message = "Property is defined here";
});
</script>

In the above code "message" is the member variable and its value is defined using $scope object. So wherever we display a message in view part its value will now get displayed as "property is defined here".

  • It is used to transfer data from view to controller as well as to transfer data from a controller to view.
  • It acts as a linking between view and controller.
  • Functions can be defined using a $scope.

$rootscope

  • An angular application contains a single $rootscope.
  • All other $scope present in an angular application are the child objects.
  • The $rootscope object is the parent of all other $scope object.
  • The behavior attached to $rootscope is available to all the controllers present in that particular angular application.
  • It means the properties and methods attached to it can be accessed by all controllers.

NOTE- The difference between $scope object and $rootscope object is that behavior attached with $rootscope is available for all the controllers while behavior attached with $scope is attached with a specific controller in which it is defined.

<html>
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
<div ng-controller="parentController">
Controller Name: {{controllerName}} <br />
Message: {{msg}} <br />
<div ng- controller="childController">
Controller Name: {{controllerName}} <br />
Message: {{msg}} <br />
</div>
</div>
<div ng-controller="siblingController">
Controller Name: {{controllerName}} <br />
Message: {{msg}} <br />
</div>
<script>
var ngApp = angular.module('myNgApp', []);
ngApp.controller('parentController', function ($scope, $rootScope) {
$scope.controllerName = "parentController";
$rootScope.msg = "Common property of all controller ";
});
ngApp.controller('childController', function ($scope) {
$scope.controllerName = "childController";
});
ngApp.controller('siblingController', function ($scope) {
$scope.controllerName = "siblingController";
});
</script>
</body>
</html>

Various Methods of $Scope Object

  1. $eval()-The current scope expression is executed and the result is displayed.
  2. $apply()-Using this method an expression can be executed in angular outside the angular framework.
  3. $new()-A new child can be created using a $new method of $scope object.
  4. $on()-A callback for an event is registered using $on a method of $scope object.
  5. $destroy()-From parent scope, a current scope can be removed using $destroy method. As well as all its child scope is also removed using from parent scope.
  6. $emit()-A particular event is dispatched upwards till $rootscope using $emit method.
  7. $broadcast()-A particular event is dispatched downwards till $rootscope using a $broadcast method.

Life Cycle of AngularJS Scope

  • In the flow of javascript code, whenever an event is received by browser then it executes a javascript callback corresponding to it.
  • And after the completion of callback, DOM objects are re-rendered by a browser.
  • If any javascript code is executed outside the context of angularJS by browser then angularJS remain unaware with the changes in the model.
  • To detect the model change in angularJS $apply API is used.
  1. Creation-During bootstrap of an application using $injector, root scope is created. And during the linking of a template, many of the directives creates new child scope.
  2. Watcher Registration-Model values can propagate to DOM using a $watch
  3. Model Mutation-To observe mutation in a proper way, an API known as $apply is used.
  4. Mutation Observation-After $apply, a $digest is performed on the root scope in angular JS.
  5. Scope Destruction-If child scope is no longer in use, then it should be destroyed. Child scope creator is responsible to destroy the child scope if no longer in use. Using API $scope.$destroy() child scope creator can do so. Destroying an unused child scope will release memory that is being used by it and stop model propagation too.

No comments:

Post a Comment