Thursday, 24 December 2015

AngularJS Interview Questions



“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.
function Customer()
{
this.CustomerName = "Ravi Gupta";
}
var Cust = new Customer();
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.
<input type=text id="TxtCustomerName" onchange="UitoObject()"/>
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.
function UitoObject()
{
Cust.CustomerName = $("#TxtCustomerName").val();
}

function ObjecttoUi()
{
$("#TxtCustomerName").val(Cust.CustomerName);
}
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.
<div ng-controller="Customer">
<input type=text id="txtCustomerName"  ng-model="CustomerName"/>
</div>
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.
1)    Some developers called it “ViewModel” because it connects the “Model” and the “View”.
2)    Some call it “Presenter” because this logic is nothing but presentation logic.
3)    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.

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.
<input type=text id="txtCustomerName"  ng-model="CustomerName"/>
Some of the most commonly used directives are ng-app, ng-controller and ng-repeat.

“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.
function Customer($scope)
{
        $scope.CustomerName = "Ravi";
        $scope.CustomerCode = "1001";
        $scope.Add = function () {
        }
        $scope.Update = function () {
        }
}
“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.
<div ng-controller="Customer">
<input type=text id="CustomerName"  ng-model="CustomerName"/><br />
<input type=text id="CustomerCode"  ng-model="CustomerCode"/>
</div>



What are expressions in Angular?
Angular expressions are unit of code which resolves to value. This code is written inside double curly braces “{“.
Below are some examples of angular expressions; the below expression adds two constant values:
{{1+1}}
The below expression multiplies quantity and cost to get the total value.
The value total cost is {{ quantity * cost }}
The below expression displays a controller scoped variable.
<div ng-controller="CustomerVM">
The value of Customer code is {{CustomerCode}}
</div>
The value of Customer code is {{CustomerCode}}

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.
<body ng-app="myApp" ng-init="pi=3.14">
The value of pi is {{pi}}
</body>



Explain $scope in Angular?
“$scope” is an object instance of a controller. “$scope” object instance gets 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.
function Function1($scope)
{
$scope.ControllerName = "Function1";       
}

function Function2($scope)
{
$scope.ControllerName = "Function2";
}
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.
<div id=&rdquo;div1&rdquo; ng-controller="Function1">
Instance of {{ControllerName}} created
</div>
<div id=&rdquo;div2&rdquo; ng-controller="Function2">
Instance of {{ControllerName}} created
</div>
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:-
1)    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.
2)    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.
1)    Step 1:- Angular parser first encounters the “ng-app” directive and creates a “$rootScope” object in memory.
2)    Step 2:- Angular parser moves ahead and finds the expression {{SomeValue}}. It creates a variable.
3)    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.
4)    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.
<script language="javascript">
function Function1($scope, $rootScope)
{
        $rootScope.Counter = (($rootScope.Counter || 0) + 1);
        $scope.Counter = $rootScope.Counter;
        $scope.ControllerName = "Function1";
}

function Function2($scope, $rootScope)
{
        $rootScope.Counter = (($rootScope.Counter || 0) + 1);
        $scope.ControllerName = "Function2";
}

    var app = angular.module("myApp", []); // creating a APP
    app.controller("Function1", Function1); // Registering the VM
    app.controller("Function2", Function2);

</script>
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.
<body ng-app="myApp" id=1>
   Global value is {{Counter}}<br />
<div ng-controller="Function1">
       Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
<div ng-controller="Function2">
       Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
<div ng-controller="Function1">
        Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
<div ng-controller="Function2">
        Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
</body>

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.

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

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

At the heart Angular framework is a parser. A parser which parses the Angular directives and render’s HTML output.
Angular parser works in 3 steps:-
Step 1:- HTML browser parses the HTML and creates a DOM (Document Object Model).
Step 2:- Angular framework runs over this DOM looks at the Angular directives and manipulates the DOM accordingly.
Step 3:- This manipulated is then rendered as HTML in the browser.
Now the above angular parsing is not as simple as it looks to be. It occurs in two phases “Compile” and “Link”. Firs the compile phase occurs then the link phase.
In compile phase the angular parser starts parsing the DOM and whenever the parser encounters a directive it create a function. These functions are termed as template or compiled functions. In this phase we do not have access to the $scope data.
In the link phase the data i.e. ($scope) is attached to the template function and executed to get the final HTML output.


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 an input in your function parameters as shown in the below code.
function CustomerController($scope,$http)
{
         $scope.Add = function()
         {
            $http({ method: "GET", url: "http://localhost:8438/SomeMethod"     }).success(function (data, status, headers, config)
                 {
                   // Here goes code after success
                 }
         }
}
“$http” service API needs at least three things:
1)    First what is the kind of call “POST” or “GET”.
2)    Second the resource URL on which the action should happen.
3)    Third we need to define the “success” function which will be executed once we get the response from the server.
$http({ method: "GET", url: "http://localhost:8438/SomeMethod"    }).success(function (data, status, headers, config)
{
// Here goes code after success
}


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.
Var myData = {};
myData.CustomerName = &ldquo;Test&rdquo;

$http({ method: "POST",
         data: myData,
         url: "http://www.xyz.com"})
         .success(function (data, status, headers, config)
         {
           // Here goes code after success
         }


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.
function Customer($scope,$http, Logger)
{
        $scope.Logger = Logger;
}
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.
var app = angular.module("myApp", []); // creating a APP
app.controller("Customer", Customer); // Registering the VM
app.service("Logger", EventLogger); // Injects a global Event logger object
So when the controller object is created the “EventLogger” object is injected automatically in the controller class.

Angular Services create and inject global instances. For example below is a simple “HitCounter” class which has a “Hit” function and this function increment the variable count internally every time you call hit the button.
function HitCounter()
{
       var i = 0;
        this.Hit = function ()
        {
            i++;
            alert(i);
        };
}
This “HitCounter” class object is injected in “MyClass” class as shown in the below code.
function MyClass($scope, HitCounter)
{
         $scope.HitCounter = HitCounter;
}
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 “HitCounter” instance.
var app = angular.module("myApp", []); // creating a APP
app.controller("MyClass", MyClass); // Registering the VM
app.service("HitCounter", HitCounter); // Injects the object
Now let’s say that the “Controller” “MyClass” is attached to two div 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.

“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 into the function.
app.service("Logger", Logger); // Injects a global object
When you define DI using a “factory” it does not create an instance. It just passes the method and later the consumer internally has to make calls to the factory for object instances.
app.factory("Customerfactory", CreateCustomer);
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.


How are validations implemented in Angular?
Angular leverages HTML 5 validations and new form element types to implement validation.
For instance below is a simple form which has two text boxes. We have used HTML 5 “required” validation attribute and a form element of type “email”.
<form name="frm1" id="frm1" >
Name :- <input type=text name="CustomerName" id="CustomerName" required />     
Email :- <input type=email  name="Email" id="Email" />
<input type=submit value="Click here"/>
</form>
Below are some examples of new form elements introduced in HTML 5 and Angular works with almost all of them:
1)    Color
2)    Date
3)    Datetime-local
4)    Email
5)    Time
6)    Url
7)    Range
8)    Telephone
9)    Number
10) Search
When you run the above HTML inside a browser which understands HTML 5 , you will see your validations and form types in actions as shown in the below browser screen shot.
Angular leverages HTML 5 validation attributes and new HTML 5 form elements. Now if we want Angular to handle validation we need first stop HTML 5 to do validation. So for that the first step is to specify “novalidate” attribute on the form tag.
<form name="frm1" novalidate>
-----
</form>
So now the HTML will not fire those validations it will be routed to the Angular engine to further take actions.
In other words when end user fills data in the HTML UI, validation events are routed to Angular framework and depending on scenario Angular sets a field called as “$Valid”. So if the validations are fine it sets it to “True” or else its sets it to “False”.

So you can see in the below code we have attached the angular controller and models to the text boxes. Watch the code of the button it has “ng-disabled” attribute which is set via the “$Valid” property in a NEGATED fashion.
Negated fashion means when there is no error it should enable the button and when there are errors that means it’s false it should disable the button.
<form name="frm1" novalidate>
Name:-<input type=text ng-model="Customer.CustomerName" name="CustomerName" required />
Email :- <input type=email ng-model="Customer.Email" name="Email" />
<input type=submit value="Click here" ng-disabled="!(frm1.$valid)"/>
</form>
Note:- “Name” is needed for the validations to work.

To check for a specific field you need to use the below DOM code.
!frm1.CustomerName.$valid


What does SPA (Single page application) mean?
SPA is a concept where rather loading pages from the server by doing post backs we create a single shell page or master page and load the webpages inside that master page.

By using Angular routes.
Implementing Angular route is a five step process:
Step 1: - Add the “Angular-route.js” file to your view.
<script src="~/Scripts/angular-route.js"></script>
Step 2: - Inject “ngroute” functionality while creating Angular app object.
var app = angular.module("myApp", ['ngRoute']);
Step 3: - Configure the route provider.
In route provider we need to define which URL pattern will load which view. For instance in the below code we are saying “Home” loads “Yoursite/Home” view and “Search” loads “YourSite/Search” view.
app.config(['$routeProvider',
            function ($routeProvider) {;

                $routeProvider.
                        when('/Home, {
                            templateUrl: 'Yoursite/Home',
                            controller: 'HomeController'
                        }).
                        when('/Search', {
                            templateUrl: YourSite/Search',
                            controller: 'SearchController'
                        }).
                        otherwise({
                            redirectTo: '/'
                        });
            }]);
Step 4: - Define hyperlinks.
Define hyper link with the “#” structure as shown below. So now when user clicks on the below anchor hyperlinks, these actions are forwarded to route provider and router provider loads the view accordingly.
Step 5: - Define sections where to load the view.
Once the action comes to the router provider it needs a place holder to load views. That’s defined by using the “ng-view” tag on a HTML element. You can see in the below code we have created a “DIV” tag with a place holder. So the view will load in this section.
So if we summarize angular routing is a three step process (Below is a visual diagram for the same): -
1)    Step 1: - End user clicks on a hyperlink or button and generates action.
2)    Step 2: - This action is routed to the route provider.
3)    Step 3: - Router provider scans the URL and loads the view in the place holder defined by “ng-view” attribute.

Explain what are the key features of Angular.js?
The key features of angular.js are:
1)    Scope
2)    Controller
3)    Model
4)    View
5)    Services
6)    Data Binding
7)    Directives
8)    Filters
9)    Testable


Explain what is scope in Angular.js?
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.

Explain what is a service in Angular.js?
In angular.js 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, and filters and so on.

What is Angular Expression? 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:
1)    Context: In Angular, the expressions are evaluated against a scope object, while the JavaScript expressions are evaluated against the global window.
2)    Forgiving: In Angular expression evaluation is forgiving to null and undefined, while in JavaScript undefined properties generate TypeError or ReferenceError.
3)    No Control Flow Statements: Loops, conditionals or exceptions cannot be used in an angular expression.
4)    Filters: To format data before displaying it you can use filters


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-init = “ loadData( )”>

What are the advantages of using Angular.js?
Angular.js has several advantages in web development.
1)    Angular.js supports MVS pattern
2)    Can do two ways data binding using Angular.js
3)    It has pre-defined form validations
4)    It supports both client server communication
5)    It supports animations


Explain what is directive and Mention what are the different types of Directive?
During compilation process when specific HTML constructs are encountered a behavior 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:
1)    Element directives
2)    Attribute directives
3)    CSS class directives
4)    Comment directives

Explain what is factory method in angular.js?
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.

What are the styling form that ngModel adds to CSS classes?
ngModel adds these CSS classes to allow styling of form as well as contrl:l
1)    ng- valid
2)    ng- invalid
3)    ng-pristine
4)    ng-dirty
Mention what are the advantages of using Angular.js framework?
Advantages of using Angular.js as framework are:
1)    Supports two way data-binding
2)    Supports MVC pattern
3)    Support static template and angular template
4)    Can add custom directive
5)    Supports REST full services
6)    Supports form validations
7)    Support both client and server communication
8)    Support dependency injection
9)    Applying Animations
10) Event Handlers


Explain the concept of scope hierarchy?  How many scopes can an application have?
Each angular application consists 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 children of their parent scope. Similar to DOM, they also create a hierarchical structure.



2 comments:

  1. Szia,


    Thank you! Thank you! Thank you! Your blog was a total game changer!


    I have biggest confusion to choose my career.
    any help me ..
    i'm a new to asp.net mvc development.

    I have some questions regarding that.

    1.Use of Entity Framework.?
    2.Why do use jquery .?
    3.AngularJS Development.?

    Can anyone suggest a couple of example.?





    Very useful article, if I run into challenges along the way, I will share them here.


    Many Thanks,

    ReplyDelete