Wednesday 25 April 2018

AngularJs Interview Question

1: What is AngularJS?
AngularJS has been introduced by the giant, Google. It is a framework that helps you to create dynamic Web apps. Normally, AngularJS uses HTML as the backbone. AngularJS creates extended HTML tags that can be used as normal HTML tags. These tags will help you to write an efficient code. The interesting fact is that you can reduce the lines of code  you may need to write when you use normal JavaScript.
AngularJS is an open-source JavaScript framework developed by Google. It is a structural framework for dynamic Web apps. It is easy to update and get information from your HTML document. It helps in writing a proper maintainable architecture, that can be tested at a client side code.
  • This framework is developed on MVC (Model-View-Controller) design pattern.
  • It provides full featured SPA (Single Page Application) framework.
  • It supports Dependency Injection.
  • It supports two-way data binding.
  • It provides routing features.
  • Testing was designed right from the beginning; so you can build robust tests.
  • For DOM manipulation, jqLite is built-in; which is kind of like the Mini-Me of jQuery.
  • Separation of the client side of an Application from the Server side.
  • The AngularJS framework uses Plain Old JavaScript Objects(POJO), it doesn’t need the getter or setter functions.
Using the code
Let's start using AngularJS. What would be the first step that you need to do? That would be to include the relevant JavaScript file as in the following:
<script src="~/Script/angular.min.js"></script>
2: Explain Directives in AngularJS?
AngularJS directives are only used to extend HTML and DOM elements' behavior. These are the special attributes, that start with ng- prefix, that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element.
AngularJS has a set of built-in directives like
  • ngBind,
  • ngModel
  • ngClass
  • ngApp
  • ngInit
  • ngRepeat
We can create our own directives for Angular to use them in our AngularJS Application with the controllers and services too. In this article, we’ll learn about some most important built-in directives like: ng-app, ng-init, ng-model, ng-bind and ng-repeat.
ng-app 
It is the most important directive for an Angular Application, which is used to indicate starting of an Angular Application to AngularJS HTML compiler ($compile), like a “Main()” function in any compile time language like C#, Java or C++ etc. If we do not use this directive first and directly try to write other directives, it gives an error. 
ng-init
ng-init directive is used to initialize an AngularJS Application data variable's inline statement, so that we can use those in the specified block where we declare them. It is like a local member of that ng-app and it can be a value or a collection of the values and as an array, it directly supports JSON data.
ng-model
ng-model directive is used to define the model/variables value to be used in AngularJS Application’s HTML controls like <input type=’text’/> and it also provides two-way binding behavior with the model value. In some cases, it’s also used for databinding.
ng-bind
ng-bind directive is also used to bind the model/variable's value to AngularJS Applications HTML controls as well as with HTML tags attributes like: <p/>, <span/> and more, but it does not support two way binding. We can just see the output of the model values.
ng-repeat
ng-repeat directive is used to repeat HTML statements. Ng-repeat works the same as for each loop in C#, Java or PHP on a specific collection item like an array.
4: Explain currency filter in AngularJS
One of the filters in AngularJS is the Currency Filter. This “currency” filter includes the “$” Dollar Symbol as the default. So we can use the following code as the html template format of Currency Filter.
{{ currency_expression | currency : symbol : fractionSize}}
How to use Currency Filter in AngularJS
There are two ways by which we can use Currency Filter.
  • Default
If we did not provide any currency symbol then by default Dollar-Sign will be used; we can use it as follows:
<!-- by default -->
  • Default Currency {{amount | currency}}
  • User Defined
To use different type of currency symbols we have to define our own symbol by using the unicode or Hexa-Decimal code of that Currency.
E.g. - For Example If we want to define Indian Currency Symbol then we have to use (Unicode-value) or (Hexa-Decimal value)
  • Indian Currency {{amount | currency:"&# 8377"}}

5: What is a Factory method in AngularJS?
AngularJS Factory: the purpose of Factory is also the same as Service, however in this case we create a new object and add functions as properties of this object and at the end we return this object.
Factories module.factory( 'factoryName', function );
Example
  • <div ng-app="Myapp">  
  •    <div ng-controller="exampleCtrl">  
  •        <input type="text" ng-model="num.firstnumber" />  
  •        <input type="text" ng-model="num.secondnumber" />  
  •        <input type="button" ng-click="Factoryclick()" value="Factoryclick" />  
  •        <input type="button" ng-click="servclick()" value="Serviceclick" /> factory result {{facresult}} service result {{secresult}}   
  •    </div>  
  • </div>   
  • var myapp = angular.module('Myapp', []);   
  • myapp.controller('exampleCtrl', ['$scope', '$http', 'factories', 'services', function (scope, http, fac, ser)   
  • {   
  • scope.Factoryclick = function ()   
  • {   
  • var firstnumber = parseInt(scope.num.firstnumber);   
  • var secondnumber = parseInt(scope.num.secondnumber);   
  • scope.facresult = fac.sumofnums(firstnumber, secondnumber);   
  • }   
  • scope.servclick = function ()   
  • {   
  • var firstnumber = parseInt(scope.num.firstnumber);   
  • var secondnumber = parseInt(scope.num.secondnumber);   
  • debugger;   
  • scope.secresult = ser.sersumofnums(firstnumber, secondnumber);   
  • }   
  • }]);   
  • myapp.factory('factories', function ($http)   
  • {   
  • return {   
  • sumofnums: function (a, b)   
  • {   
  • return a + b;   
  • }   
  • }   
  • });   
  • myapp.service('services', function ($http)   
  • {   
  • debugger;   
  • this.sersumofnums = function (a, b)   
  • {   
  • return a + b;   
  • };   
  • });   
When to use Factory: It is just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are using it with a constructor function.
6: Explain ng-app directive.
ng-app directive is used to define AngularJS applications. We can use this to auto-bootstrap an AngularJS application. It designates the root element of AngularJS application and is generally kept near
the  <body> or <html> tag. We can define any number of ng-app directives inside the HTML document but only one AngularJS application can be bootstrapped automatically (auto-bootstrapped); the other applications needs to be bootstrapped manually.
Example
  • <div ng-app="myApp" ng-controller="myCtrl">   
  •   
  • First Name :   
  •     <input type="text" ng-model="firstName">  
  •         <br />  
  • Middle Name:   
  •         <input type="text" ng-model="middleName">  
  •             <br />  
  • Last Name :   
  •             <input type="text" ng-model="lastName">  
  •                 <br>  
  •   
  • Full Name: {{firstName + " " + middleName + " " + lastName }}   
  •   
  •                 </div>  

7: Why are we using AngularJS and what are the advantages of AngularJS?
As we know AngularJS follows the  MVW* pattern and it allows us  to build well-structured, testable, and maintainable front end applications.
Note W* means "whatever," in place of which we use C (controller) or VM (view model)
Why we are using AngularJS
  1. As we know AngularJS is based on MVC pattern; it helps us to organize our web apps or web application properly. 
  2. It helps to make responsive and well organized web applications that are more expansive and readable.
  3. It follows two way data binding. Two way data binding helps us so that any changes in model will be updated view and vice-versa without any manipulation on DOM or events.
  4. AngularJS supports create your own directive that makes reusable components to be used according to your requirement. It is also abstract DOM manipulation logic.
  5. It supports services and dependency injection which we can easily inject in our controller and provides some utility code as per our requirement.
Advantages of AngularJS
1.     AngularJS has code reusability that allows us to write code & reuse it as required as Custom directive.
2.     AngularJS supports powerful data binding; it is two way data binding with the help of HTML & scope.
3.     AngularJS is easily customizable as per our requirement. Here we can create own custom components like directive and services.
4.     AngularJS has good support over the internet and over time it has new changes available for developers. It also supports IE, Opera, Safari, and Chrome.
5.     AngularJS has inbuilt form validation & template with all old plain html.
6.     AngularJS has easily testable Unit testing, it  doesn't need to load all the app, just loading that specific module is enough to start unit testing.
8: What is event handling in AngularJS?
When we want to create advanced AngularJS applications such as User Interaction Forms, then we need to handle DOM events like mouse clicks, moves, keyboard presses, change events and so on. AngularJS has a simple model for how to add event listeners. We can attach an event listener to an HTML element using one of the following AngularJS event listener directives.
  • ng-click
  • ng-dbl-click
  • ng-mousedown
  • ng-mouseup
  • ng-mouseenter
  • ng-mouseleave
  • ng-mousemove
  • ng-mouseover
  • ng-keydown
  • ng-keyup
  • ng-keypress
  • ng-change
Here is a simple AngularJS event listener directive example,
  • @{   
  • Layout = null;   
  • }   
  •   
  •   
  • <!DOCTYPE html>  
  • <html>  
  •     <head>  
  •         <meta name="viewport" content="width=device-width" />  
  •         <title>Acgular Event</title>  
  •         <script src="~/Scripts/angular.js"></script>  
  •         <script>   
  • angular.module("myapp", [])   
  • .controller("Controller1", function ($scope) {   
  • $scope.myData = {};   
  • $scope.myData.dvClick = function () {   
  • alert("Div clicked");   
  • }   
  • });   
  •   
  • </script>  
  •     </head>  
  •     <body ng-app="myapp">  
  •         <div ng-controller="Controller1">  
  •             <div ng-click="myData.dvClick()">Click here</div>  
  •         </div> 
  •     </body>  
  • </html>   
When we click the text within the div, the myData.dvClick() function will be called. As you can see in the controller function, the myData object has a dvClick() function added to it. The event listener functions called are functions added to the $scope object by the controller function.
9: What are the top reasons why developers choose AngularJS?
AngularJS, an Open Source web application framework by Google, is widely used in building highly robust and scalable Single Page Applications (SPA). Single Page Applications are websites or web applications that encompass a single web page, rendering a seamless and immersive user experience. The framework is written in JavaScript, and allows using HTML as template language. It helps build rich and intuitive web applications, and also provides web developers the option to build client-side applications.
High Performance
AngularJS is a popular choice among web developers because of  ease of use and maintenance, intuitive features, robustness, and the efficiency to build new features. It is obvious that when a problem arises, developers are not ready to spend hours debugging it. At the same time, they should be able to make minor changes with much ease. AngularJS gives you the ease of maintenance.
Effective Handling of Dependencies
AngularJS does dependency injection extremely well. For Single Page Applications, Angular makes it extremely easy to organize things like dynamic loading and dependencies, and use them as required without worrying about “Did I spin up an instance?” or “What namespace does it live in?” Simply mention what you need, and Angular will get it for you and also manage the entire life-cycle of the objects.
For testing, the framework allows you to segregate the app into logical modules that may have dependencies on each other, but are separately initialized. This helps to take a tactical approach towards testing as it provides only the modules that you need. Now, since the dependencies are injected, you can have an existing service like Angular $HTTP and swap it easily with $httpBackend mock for effective testing.
DOM has Markup in AngularJS
In most client-side JavaScript frameworks, the temples operate in something like this way,
Template with markup -> framework template engine -> HTML -> DOM 
  • However, in AngularJS, the markup is directly put into the HTML document and flow looks something like this,
 HTML with Angular markup -> DOM -> Angular Template Engin 
  • The framework evaluates the markup only when HTML has been loaded into DOM.
This has three major benefits – simplicity, integration with existing apps, and extensibility. You can work with AngularJS in basic HTML documents from a local file system. Additionally, it allows you to build custom attributes and elements that can extend the basic HTML vocabulary.

10: Explain $routeProvider in AngularJS?
The $routeProvider is used to set the configuration of urls and map them with the corresponding html page or ng-template and also attach a controller. Routing in AngularJS is taken care of by a service provide that is called $routeProvider. Routes for templates and urls in Angular are declared via the$routeProvider, that is the provider of the $route service. This service makes it easy to wire together controllers, view templates, and the current URL location in the browser.
We can use config() method of “myApp” module to configure $routeProvider. The when method of$routeProvideris used to bind the url with a template. This method takes a url(i.e. “/viewDelhi”) that will map with a template (i.e. delhi.htm) using the templateUrl parameter. The when method also binds a controller for templates using the controller parameter (i.e. controller: 'AddDelhi'), otherwise the method is used to set the default view.
Example
·         mainApp.config(['$routeProvider', function($routeProvider)  
·         {  
·             $routeProvider.  
·             when('/viewDelhi',   
·             { 
·                 templateUrl: 'delhi',  
·                 controller: 'AddDelhi'  
·             }). 
·             when('/viewMumbai',   
·             { 
·                 templateUrl: 'mumbai',  
·                 controller: 'AddMumbai'  
·             }). 
·             when('/viewJaipur',   
·             { 
·                 templateUrl: 'jaipur',  
·                 controller: 'AddJaipur'  
·             }). 
·             otherwise  
·             ({ 
·                 redirectTo: '/viewDelhi'  
·             }); 
·         }]);  
11: What are the attributes can be used during creation of a new AngularJS Directives?
  
The following attributes can be used during creation of a new AngularJS Directives,
Restrict

The restrict attribute is how AngularJS triggers the directive inside a template. The default value of the restrict option is “A”. The value of “A” causes the directives to be triggered on the attribute name. Other than “A”, restrict option has “E” (only match element name), “C” (only match class name) and “M” (only match the comment name) or any combination among four options.
 TemplateUrl

The templateUrl attribute tells the AngularJS HTML compiler to replace custom directive inside a template with HTML content located inside a separate file. The link-Menu (say, our custom directive name) attribute will be replaced with the content of our original menu template file.
 Template

Specify an inline template as a string. Not used if you’re specifying your template as a URL.
Replace

If true, replace the current element. If false or unspecified, append this directive to the current element.
Transclude

Lets you move the original children of a directive to a location inside the new template.
Scope
Create a new scope for this directive rather than inheriting the parent scope.
Controller 
Create a controller which publishes an API for communicating across directives.
Require 
Require that another directive be present for this directive to function correctly.
Link

Programmatically modify resulting DOM element instances, add event listeners, and set up data binding.
Compile
Programmatically modify the DOM template for features across copies of a directive, as when used in other directives. Your compile function can also return link functions to modify the resulting element instances.

12: What are the different types of Directives in AngularJS?
  
Directives are one of the most important components of AngularJS application. They are extended HTML attributes. In other words, directives are something that introduces new syntax. They are markers on the DOM element which provides some special behavior to DOM elements and tell AngularJS's HTML compiler to attach.

Their are many built in directives such as ng-model, ng-repeat, ng-show, ng-bind etc. All these directives provide special behavior to DOM elements. For example, ng-show directive conditionally shows an element, ng-click directive adds click events to the element; ng-app directive initializes an AngularJS application, etc.

Types of Directives

Type of directive determines how they are used. We can implement directives in the following ways,
Attribute directives Directive is active when matching attribute is found.
Example

<input type="text" numeric />   
Element directives Directive is active when matching element is found.
Example

<numeric-Textbox id = "txtAge" />   
Component directives Directive is active when matching component is found.
Example

<!-- directive: numeric-Textbox exp -->   
CSS class directives Directive is active when matching CSS style is found.
Example

<input type="text" class=" numeric "/>  
13: What is AngularJS BootStrap Process?

Bootstrapping an angular application is as simple as making coffee for yourself.
There are two ways to bootStrap Angular Application.
  • Automatic BootStrap (Coffee by Machine)
  • Manual BootStrap (Handmade coffee, you can face some trouble)

Automatic BootStrap
When DOM content is loaded, Angular looks for the ngApp directive which designates application root.
If it finds ngApp directive
a. It loads the module associated with this directive.
e.g.
<html ng-app='myApp'>  
<head>  
<script src='angular.js'>  
</script>  
<script>  
var app = angular.module('myApp', []);  
app.controller('myController', function($scope) {  
$scope.message = 'Dear';  
}); 
</script>  
</head>  
<body>
<div ng-controller="myController">  
<p> Hi {{ message}} </p>  
</div>  
From the above script, It will load "myApp".

Now let's move to the Manual process of bootstraping an Angular application.

Manual Bootstrap:

There is a big difference in Automatic and manual Bootstrap.
  1. You do not need to attach ng-app directive with the html element.
  2. You call function angular.bootstrap(document,['myApp']). 

    • <!doctype html>  
    • <html>  
    •  
    • <body>  
    •    <div ng-controller="myController"> Best movie: {{MovieName}}! </div>  
    •    <script src='angular.js'>  
    •    </script>  
    •    <script>  
    •        angular.module('myApp', []).controller('MyController', ['$scope', function($scope) {  
    •            $scope.MovieName = 'The IRON MAN';  
    •        }]);
    •        angular.element(document).ready(function() {  
    •            angular.bootstrap(document, ['myApp']);  
    •        });
    •    </script>  
    • </body>  
    •  
    • </html>  
    Angular.bootstrap can not create a module for you until you make a custom module to give it as a parameter inside.

    Before bootstrapping the process you need to add controllers, directives and services etc.

    Manual bootstrap comes into picture when you need more control over the initialization process, like if you want to perform an operation before Angular compiles a page.

    NOTE You should not use ng-app directive in case of manual bootstrapping of an angular application.

    14: What is Constants in AngularJS?

    Constant are like services in AngularJS in which we can define our global data. It is declared using "constant" keyword.

    As we define our app-keys in Web.Config file for ASP.NET application, which further we can use anywhere in the application, likewise we can declare constant data in AngularJS globally that can be used throughout the application.

    We can inject Constant everywhere in controller or service like any other dependency (e.g.$http).AngularJS uses Singleton structure for creating Constant dependency in our Angular application.

    So, using the Constant you can create your Config.js file and it can be injected anywhere in your application.

    Now, let's start to define constant and will use it in controller.

    First of all create angular module
    • var app = angular.module('ConstantApp', [])   
    Then, create Config.js file and define Constant in it,
    • app.constant('config',  
    • {  
    •    appName: 'Constants',  
    •    appVersion: 2.0  
    • });  
    Now, use the above to declare Constant in our controller,
    • app.controller('mainController', function ($scope,config) {   
    •  
    • $scope.ApplicationName = config.appName;   
    • }   
    At last now consume this scope in our HTML view,
    • <title>{{ApplicationName}}</title>   
    Conclusion

    You can use constants for a lot of things. This blog is just a basic demo explanation about constant.
    15: What is ngClass directive in AngularJS?
    ngClass directive This directive lets us do things like,
    • Add/Remove classes based on Angular variables.
    • Add/Remove classes based on evaluated expressions.
    • Bind single or multiple classes based on dynamic data.
    Some Points about ng-class
    1. The ng-class directive dynamically binds one or more CSS classes to an HTML element.
    2. The value of the ng-class directive can be a string, an object, or an array.
    3. If it is a string, it should contain one or more, space-separated class names.
    4. As an object, it should contain key-value pairs, where the key is a Boolean value, and the value is the class name of the class you want to add. The class will only be added if the key is set to true.
    Examples
    Ex 1
      • <div ng-class="{class1 : expression1, class2 : expression2}">  
      •  
      •    Hello World!  
      •  
      • </div>  


    Here class1 will apply if the expression1 is true and class2 will apply if the expression2 is true.

    Ex 2
      • < div ng-class="{'class1 class2' : expression1}">  
      •    Hello World!  
      •  
      •    < /div>  


    Here class1 and class2 will apply if the expression1 is true.

    We can reduce the above code into,
      • < div ng-class="{'class1 class2' : expression1}">  
      •    Hello World!  
      •  
      •    < /div>  

    No comments:

    Post a Comment