Top 20 AngularJS Interview Questions – MUST HAVE

By | October 16, 2016
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest

A comprehensive list of AngularJS Interview Questions and detailed answers that takes developer from entry-level to an experienced one by discussing core concepts with code samples. It’s not only helpful for an interview but also for developing professional AngularJS applications.

Below Advanced AngularJs Tutorial will also be helpful to practically grasp the technology.

AngularJS Interview Questions List

Starting with Concepts and theoratical discussion in Angularjs Tutorial

What is AngularJS?What are the key features of AngularJS? Is there any down-side of using AngularJS?

AngularJS is an open-source JavaScript system grew by Google. It helps you to make (SPA)single-page
applications or one-page web applications that just require HTML, CSS, and JavaScript on the client side. In light of MV-* design, it allows us to build very much organized, effortlessly testable, and viable front-end applications. AngularJS has adapted the best approach to web advancement.
Through it we can easily bind model data to html element, build dynamic html element, make logical decision and do both accept or send data through RESTful API.Advanced AngularJs Interview Questions and Answers

Although all this think can be done through JQuery but with AngularJS we can do all those stuff structurally. That is we can maintain a development structure which required for enterprise web application development, for example, we can extend html’s syntax and build re-useable custom component.

There is no question, JavaScript systems like AngularJS, Ember and so on are the eventual fate of web development.

AngularJS Key Features: 

  • Two way data binding: It allows us to bind data dynamically to html element that come from application’s back-end and also synchronized html element’s data value with front-end model at run-time i.e. it provide the feature of two way data binding.
  • Directive: It allows us to build re-useable custom directives. Which can save lot of time when we build large scale web application. Also it provide lots of built-in directive out of the box such as ng-repeat, ng-if, ng-model, etc. So that we can easily build single page web application.
  • Web-Service: It provide built in support for building restful and soap web service.
  • Model-View-Controller: It support concept of mode-view-controller of modern web application developed.  Through $scope provider we can make model which can be blinded to the View (HTML), and through function and restful-service ($resource, $http, etc.) we can build controller in AngularJS.
  • Routing Service: It provide built-in routing facilities through $routeProvider service.
  • Dependency Injection:  It support the concept of dependency injection like J2EE web app and Spring framework.
  • Security: We can easily implements front-end resource access controlling mechanism through various out of box component of this framework.
  • Filter:    It provide various built-in filter to convert data to desired format for view purpose such as currency, date, lowercase, uppercase, etc.

AngularJS Disadvantages/Down-side:

As this framework built upon JavaScript which is not type safe language so when application grow it become difficult to maintain source code and also difficult to find out bugs in application. This framework run base on the principle of digest look which execute all the time behind the screen which some time slow down a simple process. Some feature of AngularJS framework does not support equally in all web browser.
Back to Top

What is AngularJS Boot Process? Explain in detail with diagram?

There are two ways to initialize AngularJS to our web application:

  1. Initialized AngularJS through DOMContentLoaded event of the Browser.
  2. Manually Initialized AngularJS by calling angular.bootstrap() methods of AngularJS framework.

1) Initialized AngularJS through DOMContentLoaded event of the Browser

To initialized AngularJS through DOMContentLoaded event of the browser, we need to add “ng-app” directive to any HTML element and load the angular.js script. For example:

When we load this page in browser AngularJS initializes automatically when DOMContentLoaded event is fired that is when the initial HTML document has been completely loaded and parsed (any JavaScript in this case angular.js), without waiting for stylesheets, images, and subframes to finish loading, Then angular looks for the ngApp(i.e. ng-app) directive in this case div HTML element with id ngScope. This ngApp directive define our application root and the HTML element(in this case div with id ngScope) define the scope of the ngApp directive. If ngApp directive is found then Angular will do the following:

  • Load any module associated with the directive.
  • Create required application injector.
  • Compile the DOM that contain ng-app directive as the starting point of the compilation. This allows us to consider only a portion of the DOM (in this case div element with ngScope id) as an AngularJS application.

Below diagram show the overview of AngularJS bootstrap process:

angularjs boot process

2) Manually Initialized AngularJS by calling angular.bootstrap() methods of AngularJS framework

Through manual Initialization process we can have more control over the initialization process. In this case we need script loaders to define main app module and then as pre application requirement we can define controllers, services, directives, etc. via main app module.

Here we first create custom app module (appModule) then create the controller through this module.

Finally we load custom app module to the html DOM object by calling the angular.bootstrap() function. Note that here we pass the custom module name as second parameter of the method and must create this custom modules before we inject this as a second parameter of angular.bootstrap() function. To load controllers, services, directives, etc. we must define those before calling angular.bootstrap() function. We should not use the ng-app directive when we manually bootstrapping AngularJS application.
Back to Top

How MVC is represented in AngularJS?

Mode-View-Controller (MVC) is a design pattern. It can be represented in AngularJS framework as follow:

Model: Model in AngularJS is just a JavaScript object which contains properties either primitive such as string, integer, Boolean, array or complex type object. Its main responsibility to hold data that come from controller or service. Some time it also contains business logic which related to view.

View: It’s just a plain HTML page with embedded AngularJS directives and expression. In AngularJS we mainly represent model data through view.

Controller: It’s a JavaScript function which main responsibility to bind model data to view and vise-versa. It can also contains business logic through which it determine which model goes to which view. Controller also responsible for bind model data that come http request or other services.

We can graphically represent the MVC concept as follow:

Model View Controller

For example: Here we create a view with a customerInfoModel model and a CustomerInfoCtrl controller:

Above example we can see how customer model is blinded to view through controller. Through $scope object of AngularJS we implement two-way binding and here controller define visibility level of $scope object in the view, in this case the <body> element of the view.
Back to Top

What is routing in AngularJS? Explain in detail.

Routing is mechanism of mapping different URL request to different views of web application. We implement this functionality in AngularJS through $routeProvider.

Routing in AngularJS

As seen from the above diagram user enter a specific url into the web browser then $routeProvider load that specific web page into the web browser, it also load specific controller for that web page. We will implement this mechanism by coding as follow:

Here we load angular.js and angular-route.js script file. In the html <body> element we define ng-app module name that is routMechanism. Also here we include three hyper link through <a> which are related to customerinfo.html, productinfo.html and inventory.html page.

Next we include the ng-view directive inside the <div> element where the page content are loaded. In the main app module (appModule) we inject the ngRoute dependency. To set  up our routes we call the config method on the appModule object. The config method takes a function as its argument which is executed when the module is loaded but before the application is executed. The $routeProvider declared as a dependency to the function that is passed to the config method.

The $routeProvider is configured by calling the when() and otherwise() function. The when() function takes two parameter first one is the route path and the second one is a JavaScript object.  The route path is matched against the part of the given URL after the # when the application is loaded. The first parameter of when() function has is a JavaScript object which contains  two properties one is the templateUrl through which we set  which html page that the AngularJS should load and show inside  the <div ng-view></div> element, and through contoller property we load the specific controller for that page.

The otherwise() funciton execute when no route paths matchs with given url(In this case it load the index.html page).

[Note: The above configuration work like switch case of other programming language like C, Java,C#, etc.] Back to Top

Now Onward more Source Code/Examples in Angularjs Tutorial

Angular 4 is out now. We can use Angular 4 to develop applications that are cross platform with maximum speed and performance. More on Angular 4 here.

Indeed Job Trends

What is Scope in AngularJS? Kindly explain briefly.

Scope is a built-in service (or JavaScript object $scope) of AngularJS framework. Through $scope, controller bind model data to their views. In AngularJS scope define the relationship between controllers and views. There are two ways to use $scope within controller.

  1. We can define data(model object).
  2. We can define behaviors which are JavaScript functions.

For example here we will create two $scope object with initial data and function and also show there visibility label in DOM hierarchy through two different controllers.

To use $scope object in controller first we pass the $scope object to controller’s factory function. As seen here we define two controller CtrlFirst and CtrlSec. CtrlFirst controller’s $scope has a data property with initial value “initial date : 2016-09-10” and a behavior define by getGMTDate()function.

Similarly CtrlSec contoller’s $scope has a data property with initial value “John Abraham” and inverseCase() function.

In view we bind the CtrlFirst controller within the <div id=”first”> element, so the $scope of CtrlFirst controller is only visible with in this <div> element. Similarly $scope of CtrlSec controller is only visible within the <div id=”Second”> element.

From the above example we can see visibility level of $scope object in AngularJS is limited within specific DOM, and with the help of controller we bind $scope value and behavior to that DOM (view element).

In AngularJS there is another type of scope which is $rootScope. This $rootScope is eventually become the parent of all $scope objects. The $rootScope object act like a global context in AngularJS application. That is there is only one $rootScope object for an ng-app module.
Back to Top

What are the Controllers in AngularJS? Explain briefly.

In AngularJS Controller is special function that created from factory function provided by AngularJS framework. The main function of a controller is to pass data and behavior of $scope object between view and model (which is JavaScript object that is blinded to $scope object). Through controller we also define the visibility of $scope object in view. It is simply act a glue between the view and the $scope’s model.

From the above source code we can see here we create an “ExampleController” controller through the factory method of AngularJS framework, and also define a customerInfo model and blind it to the $scope object. The customerInfo model has three property name, address, monthlyExpense and a getCustomerCategory (expanse) function which determine the customer type either VIP or NORML. Through getCustomerCategory function we can pass expanse value from view to the customerInfo model’s function with help of ng-model, ng-change directives and via “ExampleController” controller, based on the expanse value we can see alert message with customer information either VIP or NORMAL. Here we also bind the initial value of customerInfo model’s property to the view element with help of ng-model directive and controller. Here we see how $scope’s data exchange between model and view with help of controller and directives in AngularJS framework.
Back to Top

What are the Services in AngularJS? What is the role of services in AngularJS and name any services made available by default?

In AngularJS services are used to encapsulate functionality that we want to reuse in an application. We create a service when functionality doesn’t consider to be fit in a single problem scenario or building blocks rather than for a cross-cutting concern. In AngularJS we create service through service factory function within an application module and service is singleton objects that is it’s only created ones per application module and load in memory, when it is actually needed that is service in AngularJS follow lazy loading principle like other programming language JAVA, C#, etc.

The main role of services is to provide constant interface to communicate between different controllers of an application module and keep providing data until application module exist in memory.

By default there are many built-in services exist in AngularJS framework. For example:

  • $http: Service provides low-level access to the browser’s XMLHttpRequest
  • $resource: Provides support for working with RESTful APIs.
  • $location: Provides a wrapper around the browser location object.
  • $window: Provides a reference to the DOM window object.

You can find a complete list of built-in services check the link below:

https://docs.angularjs.org/api/ng/service
Back to Top

What are expressions in AngularJS? Explain briefly with example.

In AngularJS expression use to bind model data to view (html page). We write expression inside double braces likes {{expression}}. It is a type of one way data communication that is, data only come from model to view not vise-versa. Some important points to be noted while using expression which are:

  • Expressions are not evaluated against the global window object; instead, they are evaluated against a scope object.
  • We cannot use conditionals, loops, or exceptions. This is a good thing; we don’t want complex logic inside expressions.
  • We don’t get the usual ReferenceError or TypeError when trying to evaluate undefined properties. AngularJS expressions are forgiving in that regard.
As seen for above example code, here we define a customerInfo model which has two property name and address with initialized value. In <body> element of the view we show those two property value through expression.
Back to Top

What are Directives in AngularJS? Explain ng-app, ng-init, ng-controller, ng-model, ng-bind, ng-repeat, ng-include, ng-disabled, ng-show, ng-hide, ng-click.

Directives in Angular JS are essentially JavaScript functions that are executed when the DOM is compiled by the Angular JS framework. Directives allow us to extend HTML element to create new HTML elements and it helps us to create foundation for rich and complex web applications in a way that is naturally expressive.

  • ng-app: This directive define the starting point of AngularJS application and also auto-bootstrap the application.
  • ng-init: This directive allows us to execute expression in the current scope, it also use to initializes properties of $scope variable.
  • ng-controller: Through this directive AngularJS support MVC design pattern and define scope of controller in view element.
  • ng-model: This directive use to bind input data from view to model object and vice-versa. Through this directive we can implement two-way communication between the model and view.
  • ng-bind: This directive use to bind model data to view. It represent one-way data binding.
  • ng-repeat: This directive generate dynamic elements on which it is applied, and also populate the generated contents for each object or values, in a collection. Its work like a loop of other languages such JAVA, C#, etc.
  • ng-include: This directive use to include external html page to the current html page.
  • ng-disable: This directive use to inactive an html element and it is do so by evaluation an given expression, if the given expression evaluate to true then the html element will be inactive; that is we cannot interact with that html element.
  • ng-show: This directive use to hide or show an html element, and it do so by evaluation an given expression, if the given expression evaluate to true then the html element will be shown, otherwise hide.
  • ng-hide: This directive use to hide or show an html element, and it do so by evaluation an given expression, if the given expression evaluate to true then the html element will be hiden, otherwise shown.
  • ng-click: This directive use to capture the click event of html element such as button, select, anchor ,etc. and allow us to bind functions on that event.

Back to Top

What is the difference between ng-show/ng-hide and ng-if directives?

The main difference between ng-show/ng-hide and ng-if directives are that; based on given boolean expression ng-if completely remove (if the expression evaluate to false) or recreate (if the expression evaluate to true) the html element i.e. DOM element dynamically on which ng-if directive applied.

On the other hand ng-show/ng-hide directives not remove or recreate html element i.e. DOM element dynamically, its only hide or show the html element by changing display visibility property dynamically through CSS on which ng-show/ng-hide directives applied.

So it better to use ng-if directive on html element; in such a case, when that html element contain less nested child html elements, so that remove or recreation DOM element take less time and performance of the page response not hurt.

On the other it is better to use ng-show/ng-hide directive on html element;  in such a case, when  that html element contain more nested child html elements, so that just changing the visibility of html element is better than removing that complete html element.
Back to Top

More AngularJS Interview Questions and Answers

What are Filters in AngularJS? Briefly explain uppercase, lowercase, currency filters.

In AngularJS filters transform data that goes from the scope object to the directive but don’t change the source data format. That is it, allowing us transform data only for display in views. Filter is applied to an expression by using (|) pipe operator followed by the filter name.

For example following code, show the use of uppercase, lowercase and currency filter in AngularJS:

Here we define customerInfo array which contains two customer objects; and each object has name, address, and income property. We have used the ng-repeat directive to generate rows in a table element to display the each customer objects. While displaying customer name property we pass it through uppercase filter as {{cus.name | uppercase}}, similarly address property pass through lowercase filter as {{cus.address | lowercase}} and finally we pass the income property through currency filter as {{cus.income | currency}}.

Because of uppercase filter all customer name shown in upper case letter; similarly address shown in lower case letter and because of currency filter a $ sign appended before the income value. The default currency symbol is $, but we can specify an alternative as {{cus.income | currency: “£”}} in this case British pound symbol will appended before the income value. That is after the colon (the: character) we can specify our desired the symbol that we want to express.
Back to Top

How to make an AJAX call in AngularJS? Please explain and provide an example code for making a real-time AjAX call.

In AngularJS we can use $http or $resource to make Ajax call.  For example here we will use $http service to make an Ajax call in AngularJS.  For in this example we well use a student information text file which contain json format data of some students.

By making Ajax call we will fetch the content of the studentInfo.txt file as follow:

Content of AjaxCall.html file.

[Note: To run this AjaxCall.html file in browser, we must have to put both AjaxCall.html and studentInfo.txt file in the same folder]

In the above example code we inject the $scope and $https service object into the controller, and in controller we first set url path of studentInfo.txt file then we pass that url path to the $http service’s get () method and call this method. This method return $http service object as a result, so we can chain success () callback method, which have an input parameter, that represent http response object of this Ajax call. If the get () method call is successful then the success () method will be called and bind the http response object to the studentInfo object. Finally we pass this studentInfo object to the view through $scope object and dynamically generate the student information in a table through ng-repeat directive, here success () method also return $http object as result, so we chain the error () callback method also.

However if get () method of $http service fail to fetch data from given url path then error () method will be called and print the error object’s information into the browser’s console.

Because it is an Ajax call so whatever the result of get () method and how much time it take to fetch data from text file, the browser page will be responsive all time, so that we can interact with the AjaxCall.html page while the $http.get () method is being working in background. So we click the Call me button any time to increment count value.
Back to Top

Explain two-way databinding in AngularJS with an example? Kindly provide appropriate details. Also explain the difference between one-way binding and two-way binding?

Two-way databinding in AngularJS refers to the mechanism in which we can synchronously change data between view and model, that is if we change data in view that change will be reflected in model instantly similarly if we change data in model that change reflect in the view instantly. That is we can modify data at both end; view and model.Two-Way databinding in angularjs

Above diagram show the working principle of Two-way data binding. While in One-way data binding; we can change data only at the one end (model) and other end (view) only reflect change.

One-Way Databinding

Above diagram show the working principle of One-way data binding, where we can only modify data in model, and that change will be reflected in view, here we cannot change data from view, which is main difference between one-way and two-way data binding.

In the following coding we implement two-way as well as one-way data binding as follow:

Here we create the customerInfo model with two property name and address. We initialized those two property in controller. In the view i.e. the <body> element of html page, we bind those property of the customerInfo object. First we implement one-way binding through expression {{}} and ng-bind directive.  Then we implement two-way binding through ng-model directive with help of <input> html elements.
Back to Top

How to validate data in AngularJS? Briefly explain with an example and source code.

Usually we take data from user through <form> element and submit data to the server (back-end) of web application also through form. Because <form> element of html allows us to validate data that taken from the user. AngularJS allows us to validate data of <form> element of html by providing some built-in form properties as describe in the following table:

Property

Description

$pristine Return true. If user has not yet start interacting with form element. Otherwise return false.
$dirty Return true. If user has already modify some form element’s data. Otherwise return false.
$valid Return true. If all elements of the form contains valid data. Otherwise return false.
$invalid Return true. If at least one element of the form contains invalid data. Otherwise return false.

For example consider the following HTML code:

In this above example code we include bootstrap style by providing cdn link. Here in controller of mainValidationModule module we define a customerInfo object which contains three properties fullName, address and income. In the view we make two-way binding of all three properties within <form> element and set it name attribute as name=”customerInfoForm ; and also include novalidate attribute to prevent default browser validation, this is not AngularJS directive, it is a standard HTML attribute.

Here we include required attribute to all three <input> element to make all property value mandatory for form submission. Here we also include <span> element below, to the all three <input> elements; to shows hints when a specific <input> element not have valid data; in this case the value of address property must between 3 to 50 characters and we make it possible through ng-minlength=”3″ and ng-maxlength=”50″ directives. Similarly customer’s income property value must between between 0 to 1000000 and here the input type is number. In all three <input> elements we apply has-error class base on input validity;

We determine input validity with help of customerInfoForm attribute and $invalid property of AngularJS; when we submit the form by clicking Submit Information button, submitForm() method get called. In this method we pass customerInfoForm.$valid expression as a parameter which represent a boolean value.

If the customerInfoForm.$valid expression evaluate to true then we can say all input element have valid data; that we check in the controller by give alert message; and if the customerInfoForm.$valid expression evaluate to false, then we find out which <input> element contains invalid data by evaluating “$scope.customerInfoForm.input_element_name_attribute_value.$valid” expression  which return boolean value. Base on this boolean value we show specific <span> element to provide hints to the user about the <input> element contains invalid data, by set the value of that specific ng-show directive to true.
Back to Top

What is deep linking in AngularJS? Explain in detail by providing an example.

Deep linking is process of encoding page state, such as the state of radio button, check box or the window’s current scroll position in URL. In AngularJS $routeProvider service provides a convenient interface for implementing deep linking by modifying the current URL without reloading the page.

For example, consider the URL: http://www.google.com/foo?bar=baz#qux. The three portions of a URL that we need to be familiar with are the path: /foo; the query string after ’?’ symbol: bar=baz; and the hash string after ‘#’ symbol: qux. The path and query string communicate with the server to locate precise resource we are looking for. Changing the path or the query string triggers a page reload in modern browsers. However, the browser does not send the hash portion to the server; thus, we can modify the hash component without triggering a page reload. The hash portion is typically used for deep linking functionality. For example consider the following html page:

Here the content of URL before # remain same regardless of whether we clicking hyperlink <a> First or Second. Only portion of URL after # get changed and no page reloading happening; only portion of the page that related to hyperlink get updated.
Back to Top

What is an interceptor? What are common uses of it?

Interceptors are AngularJS’s most flexible method for defining application‐level rules (security purpose) for handling HTTP requests. Suppose we wanted to attach the HTTP response status to the body of every HTTP response or we want to determine whether incoming HTTP request is valid or not. We can do this easily by using $httpProvider service provider; by implementing the concept of interceptor.

For example here we will use $httpProvider provides to implement interceptor functionality; for this example we need a json file productInfo.json, which will contains following data.

Content of productInfo.json file:

Define the interceptor.html file as follow:

[Note: To run this interceptor.html in browser we must put both interceptor.html and productInfo.json file in same directory.]

As in the preceding code, HTTP interceptors are defined as an array on the $httpProvider provider. Because providers can only be accessed in config () functions, interceptors must be defined in a config () function. Usually we insert factory functions that return objects with properties such as request, response, requestError, responseError.

But in this case, we define interceptorFunctions() function that return object which contains all the above properties and pass this $httpProvider.interceptors.push() method.

The function we have assigned to the request property illustrate how an interceptor can change a request by changing the requested URL to productInfo.json file, here we do not consider what was passed to the $http service method. To do this, we just change URL property of the config object and return this object as result so that it can be passed to the next interceptor.

For the response interceptor, we just print responses object data to the browser’s console; that we received from the server. We can also do other stuff with this object that received from server before sending it to the browser.

To complete this topic here we introduce the responseError property interceptor function which will be called when previous response interceptor throws an error.

And requestError property interceptor function which will be called when the previous request interceptor throws an error.
Back to Top

What is template in AngularJS? How would we programmatically change the template of a directive?

In AngularJS templates allows us to including external HTML into our currently loaded page in browser. The ngInclude directive is the simplest way to utilize client‐side templating. This directive enables us to replace the associated Document Object Model (DOM) element’s inner HTML with a given template’s HTML.

For example below the customerInfoTable.html file, which will act like template and will be included in the main page with the help of ngInclude directive.

Content of customerInfoTable.html file:

Content of ngIncludeExample.html file:

[Note: To run the ngIncludeExample.html fine in browser we must put both ngIncludeExample.html and customerInfoTable.html in same folder]

In the controller of ngIncludeExample.html file we define a customerInfoList which contains some customer information and we represent this information to the view through help of ngInculde directive by loading the customerInfoTable.html file. Furthermore, the ngInclude directive caches templates by their URL, so a given template is only loaded from the server once; and it also support lazy loading.

We can programmatically change the template of a directive by using the advanced compile and transclude settings. AngularJS directives’ transclude setting and its corresponding ngTransclude directive exist to reference external HTML code from within our directive’s HTML template. In other words, transclusion allows us to parameterize our directive’s template, enabling us to modify some HTML in the template based on our needs.

For example consider the html code below which dynamically change template of a directive:

As seen from the above code now we have a directive with a parameterized template. AngularJS update any HTML we put into the directive element into the directive’s template.

What IDEs you can use for AngularJS development?

AngularJS development can be done with the help of following IDEs:

  • Visual Studio 2012, 2013, 2015 or higher.
  • Eclipse
  • WebStorm
  • Sublime Text
  • TextMate

Back to Top

Learn Angular 4 (formerly Angular 2) — The Complete Guide

These web developer interview questions are really helpful for performing good in an angularjs interview as well as enhances their technical skill with the help of plenty of concepts, examples and sample code.

Good luck for your AngularJs Interview 🙂

Learn Professional Web Development in AngularJS while building 10 unique Web Apps.
77 lectures, 14.5 Hours Video, All Levels

  • Your First Angular Website
  • Web Template Store
  • myContacts App
  • ngSocial Facebook App
  • Job Directory
  • KnowledgeBase
  • User Authentication App
  • Instagram Gallery
  • PubNub Chat
  • AutoFind

And also we will find Quiz at the end of each application to verify the skill improvement.

More Web Developer Interview Questions:

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest