Tag Archives: Interview

AngularJS Interview Questions and Answers

Contents

Angular Interview questions and answers

What is AngularJS ?

Explain Directives in Angular?

What are controllers and need of ng-controller and ng-model in Angular?

What are expressions in Angular?

How can we initialize Angular application data?

Explain $scope in Angular?

What is “$rootScope” and how is it related with “$scope”?

Do I need Jquery for Angular?

How is the data binding in Angular ?

How do we make HTTP get and post calls in Angular?

How do we pass data using HTTP POST in Angular ?

What is dependency injection and how does it work in Angular?

How does DI benefit in Angular?

What are services in Angular?

Are Service object instances global or local?

What is a Factory in Angular?

What is the difference between Factory and Service?

My other interview question articles

Angular Interview questions and answers

AngularJS is one of those hot topics which interviewer’s ask for Web programming. In this article we will run through some important Interview questions around AngularJS and how we should be go about answering the same.

Do not forget to see our Learn MVC with Angular in 2 days i.e. ( 16 hours ) video series. Start from this youtube video link. https://www.youtube.com/watch?v=Lp7nSImO5vk

What is AngularJS ?

“AngularJS is a JavaScript framework which simplifies binding JavaScript objects with HTML UI elements.”

Let us try to understand the above definition with simple sample code.

Below is a simple “Customer” function with “CustomerName” property. We have also created an object called as “Cust” which is of “Customer” class type.

Now let us say the above customer object we want to bind to a HTML text box called as “TxtCustomerName”. In other words when we change something in the HTML text box the customer object should get updated and when something is changed internally in the customer object the UI should get updated.

So in order to achieve this communication between UI to object developers end up writing functions as shown below. “UitoObject” function takes data from UI and sets it to the object while the other function “ObjecttoUI” takes data from the object and sets it to UI.

So if we analyze the above code visually it looks something as shown below. Your both functions are nothing but binding code logic which transfers data from UI to object and vice versa.

Now the same above code can be written in Angular as shown below. The javascript class is attached to a HTML parent div tag using “ng-controller” directive and the properties are binded directly to the text box using “ng-model” declarative.

So now whatever you type in the textbox updates the “Customer” object and when the “Customer” object gets updated it also updates the UI.

In short if you now analyze the above code visually you end up with something as shown in the below figure.You have the VIEW which is in HTML, your MODEL objects which are javascript functions and the binding code in Angular.

Now that binding code have different vocabularies.

  • Some developers called it “ViewModel” because it connects the “Model” and the “View” .
  • Some call it “Presenter” because this logic is nothing but presentation logic.
  • Some term it has “Controller” because it controls how the view and the model will communicate.

To avoid this vocabulary confusion Angular team has termed this code as “Whatever”. It’s that “Whatever” code which binds the UI and the Model. That’s why you will hear lot of developers saying Angular implements “MVW” architecture.

Explain Directives in Angular?

Directives are attributes decorated on the HTML elements. All directives start with the word “ng”. As the name says directive it directs Angular what to do.

For example below is a simple “ng-model” directive which tells angular that the HTML textbox “txtCustomerName” has to be binded with the “CustomerName” property.

Some of the most commonly used directives are ng-app,ng-controller and ng-repeat.

What are controllers and need of ng-controller and ng-model in Angular?

“Controllers” are simple javascript function which provides data and logic to HTML UI. As the name says controller they control how data flows from the server to HTML UI.

For example below is simple “Customer” controller which provides data via “CustomerName” and “CustomerCode” property and Add/ Update logic to save the data to database.

Note: – Do not worry too much about the $scope , we will discuss the same in the next question.

“ng-controller” is a directive.Controllers are attached to the HTML UI by using the “ng-controller” directive tag and the properties of the controller are attached by using “ng-model” directive. For example below is a simple HTML UI which is attached to the “Customer” controller via the “ng-controller” directive and the properties are binded using “ng-model” directive.

What are expressions in Angular?

Angular expressionsare unit of code which resolves to value. This code is written inside curly braces “{“.

Below are some examples of angular expressions:-

The below expression adds two constant values.

The below expression multiplies quantity and cost to get the total value.

The below expression displays a controller scoped variable.

The value of Customer code is {{CustomerCode}}

How can we initialize Angular application data?

We can use “ng-init” directive to achieve the same. You can see in the below example we have used “ng-init” directive to initialize the “pi” value.

Explain $scope in Angular?

“$scope” is an object instance of a controller. “$scope” object instance get’s created when “ng-controller” directive is encountered.

For example in the below code snippet we have two controllers “Function1” and “Function2”. In both the controllers we have a “ControllerName” variable.

Now to attach the above controllers to HTML UI we need to use “ng-controller” directive. For instance you can see in the below code snippet how “ng-controller” directive attaches “function1” with “div1” tag and “function2” with “div2” tag.

So this is what happens internally. Once the HTML DOM is created Angular parser starts running on the DOM and following are the sequence of events:-

  • The parser first finds “ng-controller” directive which is pointing to “Function1”. He creates a new instance of “$scope” object and connects to the “div1” UI.
  • The parser then starts moving ahead and encounters one more “ng-controller” directive which is pointing to “Function2”. He creates a new instance of “$scope” object and connects to the “div2” UI.

Now once the instances are created, below is a graphical representation of the same. So the “DIV1” HTML UI is binded with “function1” $scope instance and the “DIV2” HTML UI is binded with “function2” $scope instance. In other words now anything changes in the $scope object the UI will be updated and any change in the UI will update the respective $scope object.

What is “$rootScope” and how is it related with “$scope”?

“$rootScope” is a parent object of all “$scope” angular objects created in a web page.

Let us understand how Angular does the same internally. Below is a simple Angular code which has multiple “DIV” tags and every tag is attached to a controller. So let us understand step by step how angular will parse this and how the “$rootScope” and “$scope” hierarchy is created.

The Browser first loads the above HTML page and creates a DOM (Document object model) and Angular runs over the DOM.Below are the steps how Angular creates the rootscope and scope objects.

  • Step 1:- Angular parser first encounters the “ng-app” directive and creates a “$rootScope” object in memory.
  • Step 2:- Angular parser moves ahead and finds the expression {{SomeValue}}. It creates a variable
  • Step 3:- Parser then finds the first “DIV” tag with “ng-controller” directive which is pointing to “Function1” controller. Looking at the “ng-controller” directive it creates a “$scope” object instance for “Function1” controller. This object it then attaches to “$rootScope” object.
  • Step 4:- Step 3 is then repeated by the parser every time it finds a “ng-controller” directive tag. Step 5 and Step 6 is the repetition of Step 3.

If you want to test the above fundamentals you can run the below sample Angular code. In the below sample code we have created controllers “Function1” and “Function2”. We have two counter variables one at the root scope level and other at the local controller level.

Below is the HTML code for the same. You can we have attached “Function1” and “Function2” two times with “ng-controller” which means four instances will be created.

Above is the output of the code you can see the global variable of root scope has be incremented four times because four instances of $scope have been created inside “$rootScope” object.

Do I need Jquery for Angular?

No , you do not need Jquery for Angular. It’s independent of Jquery.

How is the data binding in Angular ?

Its two way binding. So whenever you make changes in one entity the other entity also gets updated.

How do we make HTTP get and post calls in Angular?

To make HTTP calls we need to use the “$http” service of Angular. In order to use the http services you need to make provide the “$http” as a input in your function parameters as shown in the below code.

“$http” service API needs atleast three things:-

  • First what is the kind of call “POST” or “GET”.
  • Second the resource URL on which the action should happen.
  • Third we need to define the “success” function which will be executed once we get the response from the server.

How do we pass data using HTTP POST in Angular ?

You need to pass data using the “data” keyword in the “$http” service API function. In the below code you can see we have created a javascript object “myData” with “CustomerName” property. This object is passed in the “$http” function using HTTP POST method.

What is dependency injection and how does it work in Angular?

Dependency injection is a process where we inject the dependent objects rather than consumer creating the objects. DI is everywhere in Angular or we can go one step ahead and say Angular cannot work without DI.

For example in the below code “$scope” and “$http” objects are created and injected by the angular framework. The consumer i.e. “CustomerController” does not create these objects himself rather Angular injects these objects.

How does DI benefit in Angular?

There are two big benefits of DI: – Decoupling and Testing.

Let’s first start with Decoupling. Consider your application has a logger functionality which helps to log errors , warning etc in some central place. This central place can be a file, event viewer, database etc.

Now let’s say you have a “Customer” class who wants to use the “Logger” classes. Now which “Logger” class to use depends on configuration.

So the code of “Customer” is something as shown below. So depending on the configuration “Customer” class either creates “FileLogger” or it creates “EventLogger” object.

But with DI our code becomes something as shown below. The “Customer” class says he is not worried from where the “Logger” object comes and which type of “Logger” objects are needed .He just wants to use the “Logger” object.

With this approach when a new “Logger” object gets added the “Customer” class does not have to worry about the new changes because the dependent objects are injected by some other system.
The second benefit of DI is testing. Let’s say you want to test the “Customer” class and you do not have internet connection. So your “$http” object method calls can throw errors. But now you can mock a fake “$http” object and run your customer class offline without errors.The fake object is injected using DI.

What are services in Angular?

Service helps to implement dependency injection. For instance let’s say we have the below “Customer” class who needs “Logger” object. Now “Logger” object can be of “FileLogger” type or “EventLogger” type.

So you can use the “service” method of the application and tie up the “EventLogger” object with the “Logger” input parameter of the “Customer” class.

So when the controller object is created the “EventLogger” object is injected automatically in the controller class.

Are Service object instances global or local?

Angular Services create and inject global instances. For example below is a simple “HitCounter” class which has a “Hit” function and this function increments the variable count internally every time you call hit the button.

This “HitCounter” class object is injected in “MyClass” class as shown in the below code.

Below code advises the Angular framework to inject “HitCounter” class instance in the “MyClass” class. Read the last line of the below code specially which says to inject the inject the “HitCounter” instance.

Now let’s say that the “Controller” “MyClass” is attached to twodiv tag’s as shown in the below figure.

So two instances of “MyClass” will be created. When the first instance of “MyClass” is created a “HitCounter” object instance is created and injected in to “MyClass” first instance.

When the second instance of “MyClass” is created the same “HitCounter” object instance is injected in to second instance of “MyClass”.
Again I repeat the same instance is injected in to the second instance, new instances are not created.

If you execute the above code you will see counter values getting incremented even if you are coming through different controller instances.

What is a Factory in Angular?

“Factory” in real world means a premise where products are manufactured. Let’s take an example of a computer manufacturing firm. Now the company produces different kinds and sizes of computers likelaptops,desktops, tablets etc.

Now the process of manufacturing the computer products are same with slight variation. To manufacture any computer we need processor, RAM and hard disk. But depending on what kind of final case packing is the final product shapes.

That’s what the use of Factory in Angular.

For example see the below code we have a “Customer”, “Phone” and “Address” class.

So now we would create different types of “Customer” object types using the combination of “Address” and “Phones” object.

  • We would like to combine “Customer” with “Address” and create a “Customer” object which has “Address” collection inside it.
  • Or must be we would like to create “Customer” object with “Phone” objects inside it.
  • Or must be “Customer” object with both “Phone” and “Address” objects.

In other words we would like to have different permutation and combination to create different types of “Customer” objects.

So let’s start from bottom. Let’s create two factory function’s one which creates “Address” object and the other which creates “Phone” objects.

Now let’s create a main factory function which uses the above two small factory functions and gives us all the necessary permutation and combination.

In the below factory you can see we have three functions:-

  • “CreateWithAddress” which creates “Customer” with “Address” objects inside it.
  • “CreateWithPhone” which creates “Customer” object with “Phone” objects inside it.
  • “CreateWithPhoneAddress” which creates “Customer” object with aggregated “Phone” and “Address” objects.

Below is a simple “CustomerController” which takes “CustomerFactory” as the input. Depending on “TypeOfCustomer” it creates with “Address” , “Phones” or both of them.

You also need to tell Angular that the “CreateCustomer” method needs to be passed in the input. For that we need to call the “Factory” method and map the “CreateCustomer” method with the input parameter “CustomerFactory” for dependency injection.

So if we consume the “CustomerController” in UI , depending on situation it creates different flavors of “Customer” object. You can in the below code we have three different “DIV” tags and depending on the “TypeofCustomer” we are displaying data.

What is the difference between Factory and Service?

“Factory” and “Service” are different ways of doing DI (Dependency injection) in angular. Please read the previous question to understand what is DI.

So when we define DI using “service” as shown in the code below. This creates a new GLOBAL instance of the “Logger” object and injects it in to the function.

When you define DI using a “factory” it does not create a instance. It just passes the method and later the consumer internally has to make calls to the factory for object instances.

Below is a simple image which shows visually how DI process for “Service” is different than “Factory”.

Factory Service
Usage When we want to create different types of objects depending on scenarios. For example depending on scenario we want to create a simple “Customer” object , or “Customer” with “Address” object or “Customer” with “Phone” object. See the previous question for more detailed understanding. When we have utility or shared functions to be injected like Utility , Logger , Error handler etc.
Instance No Instance created. A method pointer is passed. Global and Shared instance is created.

My other interview question articles

jQuery, JSON and Less Interview questions with answers

http://www.codeproject.com/Articles/778374/JQUERY-JSON-Angular-and-Less-Interview-questions

100 important ASP.NET MVC interview questions

http://www.codeproject.com/Articles/556995/ASP-NET-MVC-interview-questions-with-answers

HTML 5 Interview questions with answers

http://www.codeproject.com/Articles/702051/important-HTML-Interview-questions-with-answe

WPF interview questions with answers

http://www.codeproject.com/Articles/744082/WPF-Interview-questions-with-answers

from:http://www.codeproject.com/Articles/891718/AngularJS-Interview-Questions-and-Answers

JQUERY, JSON and Angular Interview questions

What is Jquery ?

So will jquery replace javascript ?

So how do we use these reusable jquery libraries?

What is CDN (Content delivery network)?

For Jquery files which are the popular CDN’s?

How can we reference local Jquery files if CDN fails?

What is the difference between Jquery.js and Jquery.min.js file?

When should we use jquery.js over jquery.min.js ?

What is the use jquery.vsdoc.js ?

How does the basic syntax of Jquery looks like?

What is the “$” sign in Jquery ?

WhenshouldweuseJquery.noConflict()

What are the different ways by which you can select a HTML element in JQuery ?

What is the use of Document.ready in Jquery ?

Can we have two document.ready in a webpage?

What is JSON?

Do all technologies support JSON?

How can you make a JSON call using Jquery ?

How can we post JSON to Server?

How can we post a complete HTML form in JSON format?

How can we convert JSON string in to c# object?

What are single page applications (SPA)?

What is Angular JS ?

What is the need of ng-model, ng-expression and ng-app in Angular?

How is the data binding in Angular?

What is Jquery ?

Jquery is a reusable javascript library which simplifies javascript coding. So rather than writing length javascript code as below.

Collapse | Copy Code

By jquery the above javascript code is now simplified as below.

Collapse | Copy Code

If you want to kick start with Jquery start with the below video which is created by www.questpond.com

So will jquery replace javascript ?

No, Jquery is not meant to replace javascript. Jquery is a library while javascript is a language. Jquery sits on the top of javascript to make your development easy.

So how do we use these reusable jquery libraries?

You need to download Jquery.js file from jquery.com and include the same in your web pages. The jquery files are named with version number like “jquery-1.4.1.js” where 1.4.1 is the version of the JS file. So at the top of your web page you need to include the javascript as shown in the below code.

Collapse | Copy Code

What is CDN (Content delivery network)?

In CDN multiple copies of the website is copied on different geographical servers. When users request website content which have CDN enabled depending on their geographical location , content is served from the nearest geographical location server of the user.

So if a user is from India, the Indian CDN server will serve request for Indian users. This leads to faster delivery of data.

For Jquery files which are the popular CDN’s?

There are two popular CDN’s Microsoft and google.

If you want to reference google CDN Jquery files you can use the below script.

Collapse | Copy Code

If you want to use Microsoft CDN you can use the below javascript.

Collapse | Copy Code

How can we reference local Jquery files if CDN fails?

Many times it’s possible that Microsoft and google servers can go down for some time. So in those situations you would like your page to reference jquery files from local server.

So to implement a CDN fallback is a two-step process:-

First reference the CDN jquery. In the below code you can see we have reference Microsoft CDN jquery file.

Collapse | Copy Code

Now if Microsoft CDN is down then the Jquery value will be “undefined”. So you can see in the below code we are checking if the Jquery is having “undefined” value then do a document write and reference your local Jquery files.

Collapse | Copy Code

Below is the full code for the same.

Collapse | Copy Code

What is the difference between Jquery.js and Jquery.min.js file?

First thing both the files provide the same jquery functionalities. One is a long version and the other is compressed / minified version. The minified version is compressed to save bandwidth and space by compressing and removing all the white spaces.

Below is the view of Jquery.js.

Below this is view of Jquery.min.js file (compressed and minified).

When should we use jquery.js over jquery.min.js ?

When you are doing development use “jquery.js” file because you would like to debug, see the javascript code etc. Use “Jquery.min.js” for production environment. In production / live environment we would like to consume less bandwidth, we would like to our pages to load faster.

What is the use jquery.vsdoc.js ?

This file you can include if you want to enable intellisense in visual studio for Jquery.

How does the basic syntax of Jquery looks like?

Jquery syntax structure can be broken down in to four parts:-

  • All Jquery commands start with a “$” sign.
  • Followed by the selection of the HTML element. For example below is a simple image where we are selecting a HTML textbox by id “txt1”.
  • Then followed by the DOT (.) separator. This operator will separate the element and the action on the element.
  • Finally what action you want to perform on the HTML element. For instance in the below Jquery code we are setting the text value to “Hello JQuery’.

What is the “$” sign in Jquery ?

The “$” sign is an alias for jquery.

When should we use Jquery.noConflict()?

There are many javascript frameworks like MooTools, Backbone, Sammy, Cappuccino, Knockout etc. Some of these frameworks also use “$” sign so this can lead to conflict with Jquery framework.

So you can use the “noConflict” method and release the jquery “$” sign as shown in the below code.

Collapse | Copy Code

You can also create your own jquery shortcut as shown below.

Collapse | Copy Code

What are the different ways by which you can select a HTML element in JQuery ?

You can select Jquery elements in the following ways:-

Select all

Below is a simple code snippet which selects all paragraph tags and hides them.

Collapse | Copy Code

Select by ID

Collapse | Copy Code

Select using Equal method

Select using Find method

Select using Filter method

What is the use of Document.ready in Jquery ?

“Document.Ready” event occurs once the complete HTML DOM is loaded. So the next question is when do we actually need this event?. Consider the below simple code where we are trying to set a text box “text1” with value “Sometext”.

Now at the point when Jquery code tries set the textbox value , at that moment that text box is not available in the HTML DOM. So it throws an exception for the same.

Collapse | Copy Code

So we would like to execute the Jquery code which sets the textbox value only when all the HTML objects are loaded in DOM. So you can replace the code of setting text box value to something as shown below.

Collapse | Copy Code

Here is a nice detail article with a video which explains Jquery Ready event in a more detail manner http://www.dotnetinterviewquestions.in/article_jquery-interview-questions:-when-do-we-need-documentreadyevent-_230.html 

 

Can we have two document.ready in a webpage?

Yes.

How can we attach a method to a HTML element event using Jquery ?

Below is a simple code which attaches a function to click event of a button.

Collapse | Copy Code

Below is one more example where we have attached the a function to a mouse enter event of a paragraph.

Collapse | Copy Code

How can we add a style using Jquery?

$(“li”).filter(“.middle”).addClass(“selected”);

Collapse | Copy Code

What is JSON?

JSON (JavaScript object notation) helps us to present and exchange data in a self-descriptive, independent and light way. This data can then be easily consumed and transformed in to javascript objects.

Below is a simple example of JSON format looks. You can understand from the format how lightweight and easy the format looks.

Figure :- JSON

The biggest advantage of JSON format is it can be evaluated to a javascript object. For instance you can see in the below code snippet we have a JSON format data which has “name”,”street”,”age” and “phone”. Now this data can be consumed as shown in the code snippet below, evaluated to a javascript object and invoked as anobject property.

You can see how we have called the “name” property using an object “JSONObject.name”.

Collapse | Copy Code

Was not SOAP meant to do the same thing which JSON does?

SOAP is heavy due to XML tags. For example a SOAP message “Shiv” will become short , sweet and light in JSON like “Name” : “Shiv”. Second most important it evaluates as javascript object. To convert the complicated SOAP XML in to javascript JSON object would be a tough and tedious task.

Figure 11.11:- SOAP meant to do the same thing

Do all technologies support JSON?

Yes , Almost all technologies who deal with exchange of data support JSON. For instance if you want to that your WCF service should send JSON message rather than SOAP you can set the “ResponseFormat” as “WebMessageFormat.Json” on your operation contract.

Collapse | Copy Code

If you want your MVC to emit out JSON data you can return “JsonResult” as shown below. If you call the below action it will emit out Customer objects in Json format.

Collapse | Copy Code

If you want to emit JSON using ASP.NET we need to use the “DataContractJsonSerializer” class as shown in the below code.”myPerson” is the class.

Collapse | Copy Code

How can you make a JSON call using Jquery ?

Let’s assume you have a MVC controller action “getEmployee” which emits out employee JSON object as shown in the below code. Please note you can always emit JSON from any server technology like WCF , ASP.NET , MVC etc as discussed in the previous questions.

Collapse | Copy Code

To make a call to the above MVC action using Jquery we need to use “getJSON” method. Below is the simple code for the same. It has three parameters:-

  1. The first parameter is the URL which emits out JSON. For instance in the below code the URL is “/Employee/getEmployee”.
  2. The next parameter helps us to pass data to the resource which emits out JSON currently it’s the MVC action. Currently we are only doing a get so the second parameter is NULL for now.
  3. The last parameter is the call back function which will be invoked once the MVC action returns data. You can see how the “getData” function just displays the “empcode” property. Because the output is in JSON it automatically converts the JSON data to javascript object.
Collapse | Copy Code

How can we post JSON to Server?

We can use the “post” method of jquery to send data to the server. Below is how the post method call looks like. First parameter is the URL which will accept JSON data, second is the data which we want to send and the final parameter is the call back function where we receive the response.

Collapse | Copy Code

How can we post a complete HTML form in JSON format?

To post a complete HTML form we need to call “serialize” function as shown in the below code. “form1” is a HTML form. The data given by the function can then be passed to the “post” method of Jquery.”DisplayData” is a callback function to handle the output given by the server.

Collapse | Copy Code

The above posted JSON string is received at the server side “request.inputstream” , below is a simple sample code for the same.

Collapse | Copy Code

How can we convert JSON string in to c# object?

To convert a JSON string to a c# object we need to use the “JavascriptSerializer” class as shown in the below code.

“JsonString” is the string which has the JSON value and by using “Deserialize” we are converting the string to a c# object. Now this object which we receive is a collection of “key” and “value” pair which can be browsed and accessed in c#.

Collapse | Copy Code

What are single page applications (SPA)?

SPA means you web page has the following :-

  • Utilize the browser client power to the maximum by executing the maximum code on the client side by using javascript , HTML and CSS.
  • Rather than loading the complete page necessary HTML fragments or JSON data is loaded as the user demands.
  • Javascript which handles DOM manipulation, binding, Ajax calls are separated in to controllers thus separating views and models.
  • DOM manipulations are replaced by declarative programming.

What is Angular JS ?

Angular JS is JavaScript framework to create SPA applications. It simplifies complex javascript DOM manipulation code by providing declarative tags. This provides a clean separation between DOM manipulation logic and the HTML view.

For example below is a simple Angular code which helps us to display textbox data in the DIV tag when the user types in the textbox.

Collapse | Copy Code

Below is a simple video which explain Angular in 5 minutes with an example: –

 

ANGULAR JS Video

What is the need of ng-model, ng-expression and ng-app in Angular?

“ng-model” helps to store data which is typed in the HTML elements while expression helps to display the model data on the page. “ng-app” defines the root element for angular.

Below is a simple angular code which has all the three things: –

  • So whatever is typed in the textbox gets stored in the model.
  • The model is displayed by an expression {{}}.
  • “ng-app” defines the root.
Collapse | Copy Code

How is the data binding in Angular?

Its two way binding. So whenever you make changes in one entity the other entity also gets updated.

from: http://www.codeproject.com/Articles/778374/JQUERY-JSON-and-Angular-Interview-questions