LightBlog

Thursday, 13 October 2016

ANGULAR JS INTERVIEW QUESTIONS AND ANSWERS

ANGULAR JS INTERVIEW QUESTIONS



Which components can be injected as a dependency in AngularJS?
AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.
  • value
  • factory
  • service
  • provider
  • constant

What is provider?
provider is used by AngularJS internally to create services, factory etc. during config phase(phase during which AngularJS bootstraps itself). Below mention script can be used to create MathService that we've created earlier. Provider is a special factory method with a method get() which is used to return the value/service/factory.
//define a module
var mainApp = angular.module("mainApp", []);
...
//create a service using provider which defines a method square to return square of a number.
mainApp.config(function($provide) {
   $provide.provider('MathService', function() {
        
      this.$get = function() {
         var factory = {}; 
         factory.multiply = function(a, b) {
            return a * b;
         }
         return factory;
      };
                
   });
});
hat is constant?
constants are used to pass values at config phase considering the fact that value cannot be used to be passed during config phase.
mainApp.constant("configParam", "constant value");
How to implement internationalization in AngularJS?
AngularJS supports inbuilt internationalization for three types of filters currency, date and numbers. We only need to incorporate corresponding js according to locale of the country. By default it handles the locale of the browser. For example, to use Danish locale, use following script
<script src = "https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"></script>
12)  Explain what is string interpolation in Angular.js ?
In Angular.js the compiler during the compilation process matches text and attributes using interpolate service to see if they contains embedded expressions.  As part of normal digest cycle these expressions are updated and registered as watches.
24)  Explain what is the difference between AngularJS and backbone.js?
AngularJS combines the functionalities of most of the 3rd party libraries, it supports individual functionalities required to develop HTML5 Apps.  While Backbone.js do their jobs individually.
25)  Who created Angular JS ?
Intially it was developed by Misko Hevery and Adam Abrons. Currently it is being developed by Google.

10)  Explain what is data binding in AngularJS ?
Automatic synchronization of data between the model and view components is referred as data binding in AngularJS.  There are two ways for data binding
1.   Data mining in classical template systems
2.   Data binding in angular templates

5) Explain what is Angular Expression? Explain what is key difference between angular expressions and JavaScript expressions?
Like JavaScript,  Angular expressions are code snippets that are usually placed in binding such as {{ expression }}
The key difference between the JavaScript expressions and Angular expressions
·          Context : In Angular, the expressions are evaluated against a scope object, while the Javascript expressions are evaluated against the global window
·          Forgiving: In Angular expression evaluation is forgiving to null and undefined, while in Javascript undefined properties generates TypeError or ReferenceError
·          No Control Flow Statements: Loops, conditionals or exceptions cannot be used in an angular expression
·          Filters: To format data before displaying it you can use filters

What is internationalization?
Internationalization is a way to show locale specific information on a website. For example, display content of a website in English language in United States and in Danish in France.

on which types of component can we create a custom directive?
AngularJS provides support to create custom directives for following type of elements.
·        Element directives − Directive activates when a matching element is encountered.
·        Attribute − Directive activates when a matching attribute is encountered.
·        CSS − Directive activates when a matching css style is encountered.
·        Comment − Directive activates when a matching comment is encountered.

Is AngularJS extensible?
Yes! In AngularJS we can create custom directive to extend AngularJS existing functionalities.
Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using "directive" function. A custom directive simply replaces the element for which it is activated. AngularJS application during bootstrap finds the matching elements and do one time activity using its compile() method of the custom directive then process the element using link() method of the custom directive based on the scope of the directive.


What is service method?
Using service method, we define a service and then assign method to it. We've also injected an already available service to it.
mainApp.service('CalcService', function(MathService){
   this.square = function(a) {
      return MathService.multiply(a,a);
         }
});
What is factory method?
Using factory method, we first define a factory and then assign method to it.
var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {    
   var factory = {}; 
                
   factory.multiply = function(a, b) {
      return a * b
   }
   return factory;
});

What is use of $routeProvider in AngularJS?
$routeProvider is the key service which set the configuration of urls, maps them with the corresponding html page or ng-template, and attaches a controller with the same.
What is $rootScope?and $scope
Scope is a special JavaScript object which plays the role of joining controller with the views. Scope contains the model data. In controllers, model data is accessed via $scope object. $rootScope is the parent of all of the scope variables.

How to make an ajax call using Angular JS?
AngularJS provides $http control which works as a service to make ajax call to read data from the server. The server makes a database call to get the desired records. AngularJS needs data in JSON format. Once the data is ready, $http can be used to get the data from server in the following manner:
function studentController($scope,$http) {
   var url = "data.txt";
   $http.get(url).success( function(response) {
      $scope.students = response;
   });
}

Explain ng-include directive.
Using AngularJS, we can embed HTML pages within a HTML page using ng-include directive.
<div ng-app = "" ng-controller = "studentController">
   <div ng-include = "'main.htm'"></div>
   <div ng-include = "'subjects.htm'"></div>
</div>

How to validate data in AngularJS?
AngularJS enriches form filling and validation. We can use $dirty and $invalid flags to do the validations in seamless way. Use novalidate with a form declaration to disable any browser specific validation.
Following can be used to track error.
·        $dirty − states that value has been changed.
·        $invalid − states that value entered is invalid.
·        $error − states the exact error.

How angular.module works?
angular.module is used to create AngularJS modules along with its dependent modules. Consider the following example:
var mainApp = angular.module("mainApp", []);
Here we've declared an application mainApp module using angular.module function. We've passed an empty array to it. This array generally contains dependent modules declared earlier.

Following are the disadvantages of AngularJS.
·        Not Secure − Being JavaScript only framework, application written in AngularJS are not safe. Server side authentication and authorization is must to keep an application secure.
·        Not degradable − If your application user disables JavaScript then user will just see the basic page and nothing more.

Explain templates in AngularJS.
Templates are the rendered view with information from the controller and model. These can be a single file (like index.html) or multiple views in one page using "partials".
What is the difference between $parse, $interpolate and $compile services?
All those services are working together to provide a live UI in AngularJS. But they operate on different levels:
·         $parse is concerned with individual expressions only (name, extension). It is a read-write service.
·         $interpolate is read only and is concerned with strings containing multiple expressions (/path/{{name}}.{{extension}})
·         $compile is at the heart of AngularJS machinery and can turn HTML strings (with directives and interpolation expressions) into live DOM.

AngularJS provide three useful services which it uses internally., $compile, $parse, $interpolate. These service are mainly used to evaluate expression and rendering UI.

$compile: This service converts a html string in a fully functional DOM element. The resulting DOM would have all linking, events working just like a DOM element. This uses $parse internally for evaluating expressions. e.g usage of $compile would be
1
2
var html = '<div ng-click='clickme();'>{{text}}</div>';
$compile(html)($scope);
$compile is mostly used inside custom directives and doesn’t have much use outside.
$interpolate : This service is used to evaluate angular expressions. You can run an entire string against a scope, and interpolate will give the result. e.g would be
1
2
3
var string = 'My Name is {{name}}';
$scope.name = 'Manish';
$interpolate(string)($scope); //this will result in My Name is Manish
$parse : This service is used as a getter/setter for single variables only. e.g would be
1
2
3
$scope.text = 'abc';
$parse('text')($scope);  //this will result in abc
$parse('text').assign($scope,'xyz');


DropDown List
$scope.names = ["Emil", "Tobias", "Linus"];
<select ng-model="selectedName" ng-options="x for x in names"></select>
Events:
  • ng-blur
  • ng-change
  • ng-click
  • ng-copy
  • ng-cut
  • ng-dblclick
  • ng-focus
  • ng-keydown
  • ng-keypress
  • ng-keyup
  • ng-mousedown
  • ng-mouseenter
  • ng-mouseleave
  • ng-mousemove
  • ng-mouseover
  • ng-mouseup
  • ng-paste

<h1 ng-mousemove="count = count + 1">Mouse Over Me!</h1>
<button ng-click="count = count + 1">Click me!</button>
<h2>{{ count }}</h2>
To Get Co ordinate results
$scope.myFunc = function(myE) {
        $scope.x = myE.clientX;
        $scope.y = myE.clientY;
    }
<input name="myInput" ng-model="myInput" type="email">
Form State and Input State
AngularJS is constantly updating the state of both the form and the input fields.
Input fields have the following states:
  • $untouched The field has not been touched yet
  • $touched The field has been touched
  • $pristine The field has not been modified yet
  • $dirty The field has been modified
  • $invalid The field content is not valid
  • $valid The field content is valid
They are all properties of the input field, and are either true or false.
Forms have the following states:
  • $pristine No fields have been modified yet
  • $dirty One or more have been modified
  • $invalid The form content is not valid
  • $valid The form content is valid
  • $submitted The form is submitted
They are all properties of the form, and are either true or false.
You can use these states to show meaningful messages to the user. Example, if a field is required, and the user leaves it blank, you should give the user a warning:
<input name="myName" ng-model="myName" required>
<span ng-show="myForm.myName.$touched && myForm.myName.$invalid">The name is required.</span>


Concept:

$anchorScrollProvider

  1. - $anchorScroll
  2. - provider in module ng
Use $anchorScrollProvider to disable automatic scrolling whenever $location.hash() changes.
AngularJS provides $anchorScroll method to to jump to a location with specified id.
AngularJS provides $location object with hash() method to replace the current URL with a given key string.
$anchorScroll reads the hashed string and looks for the given id and jump to the section.

Methods

·         disableAutoScrolling();
By default, $anchorScroll() will automatically detect changes to $location.hash() and scroll to the element matching the new hash.
Use this method to disable automatic scrolling.
If automatic scrolling is disabled, one must explicitly call $anchorScroll() in order to scroll to the element related to the current hash
$scope.jumpToLocation = function(key){
    $location.hash(key);
    $anchorScroll();
  };


               














) What is AngularJS?
AngularJS is a javascript framework used for creating single web page applications.  It allows you to use HTML as your template language and enables you to extend HTML’s syntax to express your application’s components clearly
2) Explain what are the key features of AngularJS ?
The key features of AngularJS are
  • Scope
  • Controller
  • Model
  • View
  • Services
  • Data Binding
  • Directives
  • Filters
  • Testable
3) Explain what is scope in AngularJS ?
Scope refers to the application model, it acts like glue between application controller and the view.  Scopes are arranged in hierarchical structure and impersonate the DOM ( Document Object Model) structure of the application.  It can watch expressions and propagate events.
4) Explain what is services in AngularJS ?
In AngularJS services are the singleton objects or functions that are used for carrying out specific tasks.  It holds some business logic and these function can be called as controllers, directive, filters and so on.
5) Explain what is Angular Expression? Explain what is key difference between angular expressions and JavaScript expressions?
Like JavaScript,  Angular expressions are code snippets that are usually placed in binding such as {{ expression }}
The key difference between the JavaScript expressions and Angular expressions
  • Context : In Angular, the expressions are evaluated against a scope object, while the Javascript expressions are evaluated against the global window
  • Forgiving: In Angular expression evaluation is forgiving to null and undefined, while in Javascript undefined properties generates TypeError or ReferenceError
  • No Control Flow Statements: Loops, conditionals or exceptions cannot be used in an angular expression
  • Filters: To format data before displaying it you can use filters
6) With options on page load how you can initialize a select box ?
You can initialize a select box with options on page load by using ng-init directive
  • <div ng-controller = “ apps/dashboard/account ” ng-switch
  • On = “! ! accounts” ng-init = “ loadData ( ) ”>
7) Explain what are directives ? Mention some of the most commonly used directives in AngularJS application ? 
A directive is something that introduces new syntax, they are like markers on DOM element which attaches a special behavior to it. In any AngularJS application, directives are the most important components.
Some of the commonly used directives are ng-model, ng-App, ng-bind, ng-repeat , ng-show etc.
8) Mention what are the advantages of using AngularJS ?
AngularJS has several advantages in web development.
  • AngularJS supports MVS pattern
  • Can do two ways data binding using AngularJS
  • It has per-defined form validations
  • It supports both client server communication
  • It supports animations
9) Explain what Angular JS routes does ?
Angular js routes enable you to create different URLs for different content in your application.  Different URLs for different content enables user to bookmark URLs to specific content.  Each such bookmarkable URL in AngularJS is called a route
A value in Angular JS is a simple object.  It can be a number, string or JavaScript object.  Values are typically used as configuration injected into factories, services or controllers. A value should be belong to an AngularJS module.
Injecting a value into an AngularJS controller function is done by adding a parameter with the same name as the value
10)  Explain what is data binding in AngularJS ?
Automatic synchronization of data between the model and view components is referred as data binding in AngularJS.  There are two ways for data binding
  1. Data mining in classical template systems
  2. Data binding in angular templates
11)  What makes AngularJS better ?
  • Registering Callbacks: There is no need to register callbacks . This makes your code simple and easy to debug.
  • Control HTML DOM programmatically:  All the application that are created using Angular never have to manipulate the DOM although it can be done if it is required
  • Transfer data to and from the UI: AngularJS helps to eliminate almost all of the boiler plate like validating the form, displaying validation errors, returning to an internal model and so on which occurs due to flow of marshalling data
  • No initilization code: With AngularJS you can bootstrap your app easily using services, which auto-injected into your application in Guice like dependency injection style
12)  Explain what is string interpolation in Angular.js ?
In Angular.js the compiler during the compilation process matches text and attributes using interpolate service to see if they contains embedded expressions.  As part of normal digest cycle these expressions are updated and registered as watches.
13)  Mention the steps for the compilation process of HTML happens?
Compilation of HTML process occurs in following ways
  • Using the standard browser API, first the HTML is parsed into DOM
  • By using the call to the $compile () method, compilation of the DOM is performed.  The method traverses the DOM and matches the directives.
  • Link the template with scope by calling the linking function returned from the previous step
14)  Explain what is directive and Mention what are the different types of Directive?
During compilation process when specific HTML constructs are encountered a behaviour or function is triggered, this function is referred as directive.  It is executed when the compiler encounters it in the DOM.
Different types of directives are
  • Element directives
  • Attribute directives
  • CSS class directives
  • Comment directives
15)  Explain what is linking function and type of linking function?
Link combines the directives with a scope and produce a live view.  For registering DOM listeners as well as updating the DOM, link function is responsible. After the template is cloned it is executed.
  • Pre-linking function: Pre-linking function is executed before the child elements are linked.  It is not considered as the safe way for DOM transformation.
  • Post linking function: Post linking function is executed after the child elements are linked. It is safe to do DOM transformation by post-linking function
16)  Explain what is injector?
An injector is a service locator.  It is used to retrieve object instances as defined by provider, instantiate types, invoke methods and load modules.  There is a single injector per Angular application, it helps to look up an object instance by its name.
17)  Explain what is the difference between link and compile in Angular.js?
  • Compile function: It is used for template DOM Manipulation and collect all of the directives.
  • Link function: It is used for registering DOM listeners as well as instance DOM manipulation. It is executed once the template has been cloned.
18)  Explain what is factory method in AngularJS?
For creating the directive, factory method is used.  It is invoked only once, when compiler matches the directive for the first time.  By using $injector.invoke the factory method is invoked.
19)  Mention what are the styling form that ngModel adds to CSS classes ?
ngModel adds these CSS classes to allow styling of form as well as control
  • ng- valid
  • ng- invalid
  • ng-pristine
  • ng-dirty
20)  Mention what are the characteristics of “Scope”?
  • To observer model mutations scopes provide APIs ($watch)
  • To propagate any model changes through the system into the view from outside of the Angular realm
  • A scope inherits properties from its parent scope,  while providing access to shared model properties, scopes can be nested to isolate application components
  • Scope provides context against which expressions are evaluated
21)  Explain what is DI (Dependency Injection ) and how an object or function can get a hold of its dependencies ?
DI or Dependency Injection is a software design pattern that deals with how code gets hold of its dependencies.  In order to retrieve elements of the application which is required to be configured when module gets loaded , the operation “config” uses dependency injection.
These are the ways that object uses to hold of its dependencies
  • Typically using the new operator, dependency can be created
  • By referring to a global variable, dependency can be looked up
  • Dependency can be passed into where it is required
22)  Mention what are the advantages of using Angular.js framework ?
Advantages of using Angular.js as framework are
  • Supports two way data-binding
  • Supports MVC pattern
  • Support static template and angular template
  • Can add custom directive
  • Supports REST full services
  • Supports form validations
  • Support both client and server communication
  • Support dependency injection
  • Applying Animations
  • Event Handlers
23)  Explain the concept of scope hierarchy?  How many scope can an application have?
Each angular application consist of one root scope but may have several child scopes. As child controllers and some directives create new child scopes, application can have multiple scopes. When new scopes are formed or created they are added as a children of their parent scope. Similar to DOM, they also creates a hierarchical structure.
24)  Explain what is the difference between AngularJS and backbone.js?
AngularJS combines the functionalities of most of the 3rd party libraries, it supports individual functionalities required to develop HTML5 Apps.  While Backbone.js do their jobs individually.
25)  Who created Angular JS ?
Intially it was developed by Misko Hevery and Adam Abrons. Currently it is being developed by Google.


16. Can angular applications (ng-app) be nested within each other?
NO. AngularJS applications cannot be nested within each other.

13. What are the different types of Directive?
  • Element directives
  • Attribute directives
  • CSS class directives
  • Comment directives
11. Is AngularJS same as jQuery?
·         NO. jQuery is great library for manipulating the DOM, providing better user experience with animations and effects. You can create website using jQuery but not a web application. jQuery is just a library to play around with HTML, where as AngularJS is a framework to build a dynamic web app as it supports two data binding, MVC, allow testability, templates and many more. AngularJS is like a toolbox and jQuery is just a tool.

10. Does Angular use the jQuery library?
·         Yes, Angular can use jQuery if you have included the jQuery library.
If jQuery is not present in our script path, Angular falls back to its own implementation of the subset of jQuery that we call as jQLite.
18. How to initiate variable in AngularJS?
         <div ng-app="" ng-init="quantity=10;cost=5">
             <b>Total Cost: {{ quantity * cost }}</b>
         </div>

22. What is ng-model in AngularJS?
To bind the html tags (input, select, textarea) to Angular Application Dat

24. What Angular JS routes does?
Angular js routes enable you to create different URLs for different content in your application. Different URLs for different content enables user to bookmark URLs to specific content. Each such bookmarkable URL in Angular.js is called a route.
A value in Angular JS is a simple object. It can be a number, string or JavaScript object. Values are typically used as configuration injected into factories, services or controllers. A value should be belong to an Angular.js module.
Injecting a value into an Angular.js controller function is done by adding a parameter with the same name as the value.
For angular custom directive the best practice is to follow camel casing and that also with atleast two letter’s. In camel case naming convention we start with a small letter, followed by a capital letter for every word.
Some example of camel cases are “loopCounter” , “isValid” and so on.

Explain $q service, deferred and promises?

Promises are POST PROCESSING LOGICS which you want to execute after some operation / action is completed. While deferred helps to control how and when those promise logics will execute.
We can think about promises as “WHAT” we want to fire after an operation is completed while deferred controls “WHEN” and “HOW” those promises will execute.
For example after an operation is complete you want to a send a mail, log in to log file and so on. So these operations you will define using promise. And these promise logics will be controlled by deferred.
We are thankful to www.stepbystepschools.net for the above image.
So once some action completes deferred gives a signal “Resolve”, “Reject” or “Notify” and depending on what kind of signal is sent the appropriate promise logic chain fires.
“$q” is the angular service which provides promises and deferred functionality.
Using promises, deferred and “q” service is a 4 step process:-
·         Step 1:- Get the “q” service injected from Angular.
·         Step 2 :- Get deferred object from “q” service object.
·         Step 3 :- Get Promise object from deferred object.
·         Step 4 :- Add logics to the promise object.
Below is the angular code for the above 4 steps.
Hide   Copy Code
// Step 1 :- Get the "q" service
    function SomeClass($scope,$q) {
 
// Step 2 :- get deferred  from "q" service
        var defer = $q.defer();
// step 3:-  get promise  from defer
        var promise = defer.promise;
// step 4 :- add success and failure logics to promise object
promise.then(function () {
            alert("Logic1 success");
        }, function () {
            alert("Logic 1 failure");
        });
 
promise.then(function () {
            alert("Logic 2 success");
        }, function () {
            alert("Logic 2 failure");
        });
 
    }
So now depending on situations you can signal your promise logics via deferred to either fire the success events or the failure events.
Hide   Copy Code
// This will execute success logics of promise 
defer.resolve();
Hide   Copy Code
// This will execute failure logics of promise
defer.reject();

Yes, you can set template to page directly by using “templateUrl” property of the directive as shown in the code snippet below.
Hide   Copy Code
directive.templateUrl = "/templates/footer.html";

5. What is linking function?
Link combines the directives with a scope and produce a live view. For registering DOM listeners as well as updating the DOM, link function is responsible. After the template is cloned it is executed.
26.What is Pre-linking function and Post-linking function in AngularJS?
Pre-linking function is executed before the child elements are linked. It is not considered as the safe way for DOM transformation.
Post linking function is executed after the child elements are linked. It is safe to do DOM transformation by post-linking function.
27. Explain what is the difference between link and compile in angular.js?
  • Compile function: It is used for template DOM Manipulation and collect all of the directives.
  • Link function: It is used for registering DOM listeners as well as instance DOM manipulation. It is executed once the template has been cloned.
·         It is possible to have multiple or nested views. But not by ng-view.
·         The primary routing module in angular does not support multiple views. But you can use ui-router. This is a third party module which you can get via Github, angular-ui/ui-router, https://github.com/angular-ui/ui-router . Also a new version of ngRouter (ngNewRouter) currently, is being developed. It is not stable at the moment. So I provide you a simple start up example with ui-router. Using it you can name views and specify which templates and controllers should be used for rendering them. Using $stateProvider you should specify how view placeholders should be rendered for specific state.
·         <body ng-app="main">
·             <script type="text/javascript">
·             angular.module('main', ['ui.router'])
·             .config(['$locationProvider', '$stateProvider', function ($locationProvider, $stateProvider) {
·                 $stateProvider
·                 .state('home', {
·                     url: '/',
·                     views: {
·                         'header': {
·                             templateUrl: '/app/header.html'
·                         },
·                         'content': {
·                             templateUrl: '/app/content.html'
·                         }
·                     }
·                 });
·             }]);
·             </script>
·             <a ui-sref="home">home</a>
·             <div ui-view="header">header</div>
·             <div ui-view="content">content</div>
·             <div ui-view="bottom">footer</div>
·             <script src="bower_components/angular/angular.js"></script>
·             <script src="bower_components/angular-ui-router/release/angular-ui-router.js">
·         </body>



Quizz
Data binding can be done in two ways in Angular js - data binding in classical template systems and data binding in angular templates?yes
ng-init directive in angular js is used for?
Wraps a raw DOM element or HTML string as a jQuery element
Allows you to evaluate an expression in the current scope
Determines if two objects or two values are equivalent.
Serializes input into a JSON-formatted string

What is the factory method is used for?
It is used for creating the directive
It is used for template DOM manipulation
It is used for styling of form
To check how code gets hold of its dependencies

How does an object or function can get hold of its dependencies in angular js?
Typically using the new operator, dependency can be created
By referring to a global variable, dependency can be looked up
Dependency can be passed into where it is required
All of the abov
What is link function is used for in angular js?
It is used for registering DOM listeners as well as instance DOM manipulation
It is used to retrieve object instances as defined by provider
It is used for template DOM Manipulation and collect all of the directives
The method traverses the DOM and matches the directives
Explain what Angular JS routes does?
Automatic synchronization of data between the model and view components
Enables you to create different URLs for different content in your application
Link the template with scope by calling the linking function returned from the previous step
To propagate any model changes through the system into the view from outside of the Angular realm


2 comments:

  1. Thanks for sharing the knowledgeable stuff to enlighten us no words for this amazing blog.. learnt so many things I recommend everyone to learn something from this blogger and blog.. I am sharing it with others also
    IT Software Training in Chennai | Python Training in Chennai | Dot Net Training in Chennai |Android Training in Chennai

    ReplyDelete

LightBlog