Total Pageviews

Monday 18 March 2019

AngularJS Life Cycle


Whenever an AngularJS application loads in the browser, it consists 3 phases mentioned below:

Bootstrap – This phase occurs when the AngularJS JavaScript library is downloaded into the browser. After that AngularJS initializes their own necessary components and then initializes our application module, which the ng-app directive points to. Once the module is loaded, and if there are any dependencies injected into our application module, then that module is available within the module.

Compilation- In this phase static HTML DOM is replaced with dynamic HTML DOM which is referred as AngularJS view.

This phase itself consist of two phases:

Compile: In this phase AngularJS traverses the static DOM and collects all the directives.

Link: All the directives linked to the respective JavaScript functionality present in the AngularJS built-in library or in the custom directive code. All the directives has their own scope’s to produce the dynamic view.

Runtime Data Binding- This is the final phase of the AngularJS, this phase exists until the user reloads the web page or navigates away from a web page. At this point, any changes happens in the scope are reflected in the view, and any changes happens in view are directly updated in the scope. Which makes the scope the only source of data for the view.

Wednesday 13 March 2019

Digest Cycle | AngularJS


Digest Cycle

We can consider digest cycle as a loop in which AngularJS checks if there are any changes to the variables watched by respective $scope’s. If we want to monitor the changes of a variable then we can mark them for being watched.  This process is called as digest cycle or loop.

The good thing is that, everything attached to the scope is not being watched; else it would have been a serious performance issue as digest cycle loop through the variables to check the changes.

$watch(), $digest() and $apply()
are the AngularJS $scope functions.


Use $watch to listen for $scope changes

There are 2 ways to watch a scope variable.

1)   via expression <span>{{ clientId}}</span>
2)   via the $watch service

To explain first point, Expressions “{{}}” creates a watch in the background. And AngularJS directives (such as ng-repeat) can also create implicit watches.

To explain second point, we can also create custom watches. $watch service helps to run any code when any value attached to the $scope has changed. It is not recommended to use explicit watches but sometimes it is helpful.

For instance, if we want to run some code each time ‘clientId’ changes, we could do the following:

function clientController($scope) {

    $scope.clientId = 1;

    $scope.$watch('clientId ', function() {
        alert(‘clientId has changed!');
    });

    $scope.buttonClicked = function() {
        $scope.clientId = 2; // This will trigger $watch expression to kick in
    };
}

Use $apply to make changes with the digest cycle

Sometimes we need to set a variable value on completion of a particular task. But AngularJS can't wait for this to happen, since it hasn't been instructed to wait on anything.

To avoid this scenario, $apply has been introduced. It is used to execute the desired code, and after that $scope.$digest() is called, so all watches are checked and their corresponding listener functions are called.

However, $scope.$digest() should only use to integrate with other code, but not with regular AngularJS code, as AngularJS will throw an error then. The $digest() function triggers the data binding to HTML view.


Tuesday 12 March 2019

Dynamic Table ADD/DELETE Row in AngularJS1

I have created a simple demo to show how to add and delete a table row dynamically in AngularJS1

Please don't mind my HTML view, as this demo is totally focused on functionality.

HTML


<!DOCTYPE html> 
<html lang="en" ng-app="app" ng-controller="appCtrl">
   <head>
      <title>Dynamic Table</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="initial-scale=1,user-scalable=no">
      <meta http-equiv="X-UA-Compatible" content="IE=10" />
      <meta name="apple-mobile-web-app-capable" content="yes" />
      <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>     <script src="app.js"></script>   
   </head>
   <body>
      <div class="container">
         <div class="row">
            <div class="col-12 col-sm-12 col-md-12 col-lg-12">
               <table class="table table-bordered mt-3">
                  <thead>
                     <th ng-repeat="(key, val) in tblRows[0]">                 {{key}}               </th>
                  </thead>
                  <tbody>
                     <tr ng-repeat="list in tblRows">
                        <td>                   {{list.id}}                 </td>
                        <td>                   {{list.name}}                 </td>
                        <td>                   {{list.email}}                 </td>
                     </tr>
                  </tbody>
               </table>
            </div>
         </div>
         <div class="row">
            <div class="col-12 col-sm-12 col-md-12 col-lg-12 mt-4">
               <form name="dataForm" novalidate>
                  <div>Create Table</div>
                  <p class="mt-4">               <input name="id" type="number" placeholder="Enter Id" ng-model="id" required />               <span style="color:red" ng-show="dataForm.id.$dirty && dataForm.id.$error.required">Id is               required</span>             </p>
                  <p>               <input name="name" type="text" placeholder="Enter Name" ng-model="name" required />               <span style="color:red" ng-show="dataForm.name.$dirty && dataForm.name.$error.required">Name is               required</span>             </p>
                  <p>               <input name="email" type="email" placeholder="Enter Email" ng-model="email" required />               <span style="color:red" ng-show="dataForm.email.$dirty && dataForm.email.$error.required">Email               is required</span>             </p>
                  <div style="color:red">{{displayMsg}}</div>
                  <div class="row mt-5 float-right">
                     <div class="col-12 col-sm-12 col-md-12 col-lg-12">
                        <div class="row">                   <input type="button" value="ADD" ng-click="addRow()" ng-disabled="dataForm.$invalid" />                   <input type="button" class="ml-2" value="DELETE" ng-click="deleteRow()"                     ng-disabled="tblRows.length==0" />                 </div>
                     </div>
                  </div>
               </form>
            </div>
         </div>
      </div>
   </body>
</html>
AngularJS
var myApp = angular.module("app", []);
myApp.controller("appCtrl", function ($scope) {
 $scope.tblRows = [{
  "id": 1,
  "name": "Swati",
  "email": "abc@xyz.com"
 }];
 $scope.addRow = function () {
  var checkIfExist = Object.keys($scope.tblRows).some(function (k) {
   return $scope.tblRows[k].id === $scope.id;
  });
  console.log("checkIfExist  ", checkIfExist);
  if (!checkIfExist) {
   $scope.tblRows.push({
    "id": $scope.id,
    "name": $scope.name,
    "email": $scope.email
   });
   $scope.displayMsg = "";
   $scope.id = '';
   $scope.name = '';
   $scope.email = '';
   $scope.dataForm.$setPristine();
   console.log($scope.dataForm.$pristine)
  } else {
   $scope.displayMsg = "Id already exists!";
  }
 }
 $scope.deleteRow = function () {
  $scope.tblRows.pop();
  $scope.displayMsg = "";
 }
});

Saturday 9 March 2019

AngularJS | Ways to implement Dependency Injection


There are 5 ways to implement Dependency Injection in AngularJS:

· Value

· Constant

· Factory

· Providers

· Services

We are going to look into each one by one:

Value: Value function is used to initialize any variable such as number, string or object. It is required to pass values to the controller during config or run phase (config or run phase is when AngularJS bootstraps itself) which is then injected into factories, services or controllers.

Example:

//define a module
var testApp = angular.module([]);

//create a value object and pass it a data 
testApp.value("numberValue", 1100); 

Injecting a value

testApp.controller("testCtrl", function ($scope, numberValue) {
    console.log("numberValue",numberValue);
}


Constant:

Unfortunately we cannot inject values into the module.config() function. But we can inject constants. Constant value is used when we want to do any configuration such as in any routing program.

Example:

Injecting a constant

var testApp = angular.module([]);

testApp.constant("configParam", "constant value");   

testApp.config(function (serviceProvider, configParam) {
    serviceProvider.doConfig(configParam)
}


Factory:

A factory is a simple function which allows us to add some logic before creating the object. It returns the created object. It injects the values whenever service or controller needs a value. It returns the value on demand and uses “factory” function to process and return the value.

Example:

var testApp = angular.module([]);

testApp.value("numberValue", 1100); 
testApp.factory("addNum", function (numberValue) {
return "numberValue is "+numberValue;
});

testApp.controller("testCtrl", function ($scope, addNum) {
    console.log("addNum ", addNum);
}

Service:

It is a singleton object and contains set of functions to perform certain tasks. Services are created by using service() function on a module and then injected into controllers. It is injected into controllers.

For example, the "$http" is a service in Angular.JS which when injected in your controllers provides the necessary functions of ( get() , query() , save() , remove(), delete() ).

Example:

var testApp = angular.module([]);

testApp.service('addService', function(){
    this.add = function(a,b) {
        return a+b;
    }
});

testApp.controller("testCtrl", function ($scope, addService) {
    console.log(addService.add(1,6));
}

It is used when we need to share a single object across the application such as, authenticated user details.

Provider:

Provider is itself is a factory. It allows us to create services, factory etc during config phase that is on runtime. It uses get() function to return the value or service or factory.

Example:

var testApp = angular.module([]);

testApp.config(function($provide) {
    $provide.provider('MathService', function() {
       this.$get = function() {
          var factory = {};
         
          factory.multiply = function(a, b) {
             return a * b;
          }
          return factory;
       };
    });
 });

testApp.service('CalService', function(MathService){ 
    this.square = function(a) { 
       return MathService.multiply(a,a); 
    } 
 });

testApp.controller("testCtrl", function ($scope, $state, CalService) {

    $scope.result = CalcService.square(5); 
    console.log("aaa ", $scope.result)

});



It is used when we need to provide module-wise configuration for service object before making it available.

Thursday 7 March 2019

AngularJS | Dependency Injection


Dependency Injection ( DI ) :

Dependency is an object of a class which a class needs to function. For example, we have a model class which fetches data from database object. Hence we can say that model class has a dependency on database object.

So what does it mean by Injecting Dependency: It means that the dependency is pushed into the class from the outside i.e. we don’t need to instantiate the dependencies from inside the class using “new” keyword. Instead we should take dependency as parameters using constructors, setters and services.

In a simple word we can say that

“It’s a pattern used to create instances of object and passing into other objects by using constructors, setters and services.”

Or

“Passing more parameters in constructor” is called Dependency Injection.

Also, AngularJs comes with built-in dependency injection mechanism, i.e, it is help us to divide our application into multiple different components which can be injected into each other as dependencies.

Why Dependency Injection ( DI ) :

1. Dependency Injection is a method for writing better code.

2. It decouple the objects which are dependent on each other so that we don’t need to instantiate object using “new” keyword.

3. DI makes testing of components easier.

4. DI increase efficiency of code.

5. It allows the code to be modular.

Example:

Without Dependency Injection:

var empl = function(age, name){
        this.age = age;
        this.name = name;
    }

    function addPerson(){
        var getEmpl = new empl(25, "Swati");
    }

    addPerson();

With Dependency Injection:

    var empl = function(age, name){
        this.age = age;
        this.name = name;
    }

    function addPerson(getEmpl){
      //ToDo
    }
    var getEmpl = new empl(25, "Swati");

    addPerson(getEmpl);


So what we have gotten from the above code is that by using Dependency Injection, we don’t need to change the method every time. Only the passing value will change.

Types of Dependency injection:

1. Constructor Injection – When we provide dependency through the constructor then its constructor injection.


Example:
       var getEmpl = new empl(25, "Swati");

       addPerson(getEmpl);


Here we have passed the values inside “empl” constructor.

2. Setter/Getter Injection - Dependency is provided through setter/getter method.

Example:
class Person{
    private Age ag;
   
    // Setter Based
    void setAge(Age age){
      this.age = age;
    }
    // code 
  }

3.    Interface Injection - Dependencies are provided through methods.

4.  app.factory("addNum", function () {
5.   
6.          return {
7.              add: function (a, b) {
8.                  return a + b;
9.              }
10.        }
11.    });
12. 
13.    app.controller('NumCtrl', CalController);
14.    NumCtrl.$inject = ['$scope', 'addNum'];

Here, instead of passing dependencies as function we will inject the dependencies using the $inject.


Despite being a great concept DI also has some disadvantages:

1. It’s a bit complex concept to learn

2. Over usage can lead to management issues and other problems.

3. Many compile time errors occurs at run-time.

Thanks

Tuesday 5 March 2019

20 AngularJS Interview Questions

1. What is the difference between Angular and jQuery?
2. What are the features of AngularJS?
3. What are directives in AngularJS?
4. How to create custom directives in AngularJS?
5. What are Controllers in AngularJS?
6. What is scope in AngularJS?
7. What is difference between scope and $scope in AngularJS?
8. What is the difference between $scope and $rootscope in AngularJS?
9. What are the advantages of AngularJS?
10. What are the difference between AngularJS and Angular2?
11. Why should we use AngularJS?
12. What is data binding in AngularJS?
13. What is bootstrapping in AngularJS?
14. What is SPA (Single Page Application)?
15. Can we use nested controllers in AngularJS?
16. Can we have multiple ng-app in AngularJS?
17. What is ng-app, ng-init, and ng-model?
18. Does AngularJS use jQuery library?
19. What is factory in AngularJS?
20. What is injector in AngularJS?


Microsoft Logo using flexbox and Reactjs

 <!DOCTYPE html> <html> <head>     <script src="https://unpkg.com/react@18/umd/react.development.js" crossori...