Angular JS Interview

Angualr JS Interview Questions and Answers

Q. What is AngularJS?

Ans. AngularJS is an open-source JavaScript framework developed by Google. It helps you to create single-page applications or one-page web applications that only require HTML, CSS, and JavaScript on the client side. It is based on MV-* pattern and allow you to build well structured, easily testable, and maintainable front-end applications.

AngularJS has changed the way to web development. It is not based on jQuery to perform its operations. In spite of using ASP.NET Web form, ASP.NET MVC, PHP, JSP, Ruby on Rails for web development, you can do your complete web development by using most powerful and adaptive JavaScript Framework AngularJS. There is no doubt, JavaScript frameworks like AngularJS, Ember etc. are the future of web development.

Q. Why to use AngularJS?

Ans. There are following reasons to choose AngularJS as a web development framework:

  1. It is based on MVC pattern which helps you to organize your web apps or web application properly.
  2. It extends HTML by attaching directives to your HTML markup with new attributes or tags and expressions in order to define very powerful templates.
  3. It also allows you to create your own directives, making reusable components that fill your needs and abstract your DOM manipulation logic.
  4. It supports two-way data binding i.e. connects your HTML (views) to your JavaScript objects (models) seamlessly. In this way any change in model will update the view and vice versa without any DOM manipulation or event handling.
  5. It encapsulates the behaviour of your application in controllers which are instantiated with the help of dependency injection.
  6. It supports services that can be injected into your controllers to use some utility code to fulfil your need.
  7. For example, it provides $http service to communicate with REST service.
  8. It supports dependency injection which helps you to test your angular app code very easily.
  9. Also, AngularJS is mature community to help you. It has widely support over the internet.

Q. Why this project is called “AngularJS”?

Ans. Html has angle brackets i.e. <,> and ng sound like Angular. That’s why it is called AngularJS.

Q. What are the advantages of AngularJS?

Ans. There are following advantages of AngularJS:

  • Data Binding – AngularJS provides a powerful data binding mechanism to bind data to HTML elements by using scope.
  • Customize & Extensible – AngularJS is customized and extensible as per you requirement. You can create your own custom components like directives, services etc.
  • Code Reusability – AngularJS allows you to write code which can be reused. For example custom directive which you can reuse.
  • Support – AngularJS is mature community to help you. It has widely support over the internet. Also, AngularJS is supported by Google which gives it an advantage.
  • Compatibility – AngularJS is based on JavaScript which makes it easier to integrate with any other JavaScript library and runnable on browsers like IE, Opera, FF, Safari, Chrome etc.
  • Testing – AngularJS is designed to be testable so that you can test your AngularJS app components as easy as possible. It has dependency injection at its core, which makes it easy to test.

Q. How AngularJS is different from other JavaScript Framework?

Ans. Today, AngularJS is the most popular and dominant JavaScript framework for professional web development. It is well suited for small, large and any sized web app and web application.

AngularJS is different from other JavaScript framework in following ways:

  1. AngularJS mark-up lives in the DOM.
  2. AngularJS uses plain old JavaScript objects (POJO).
  3. AngularJS is leverages with Dependency Injection.

Q. What IDEs you can use for AngularJS development?

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

  1. Visual Studio 2012, 2013, 2015 or higher
  2. Eclipse
  3. WebStorm
  4. Sublime Text
  5. TextMate

Q. Does AngularJS has dependency on jQuery?

Ans. AngularJS has no dependency on jQuery library. But it can be used with jQuery library.

Q. How to use jQuery with AngularJS?

Ans. By default AngularJS use jQLite which is the subset of jQuery. If you want to use jQuery then simply load the jQuery library before loading the AngularJS. By doing so, Angular will skip jQLite and will started to use jQuery library.

Q. Compare the features of AngularJS and jQuery?

Ans. The comparison of AngularJS and jQuery features are given below:

Features jQuery AngularJS
Abstract The DOM Y Y
Animation Support Y Y
AJAX/JSONP Y Y
Cross Module Communication Y Y
Deferred Promises Y Y
Form Validation N Y
Integration Test Runner N Y
Unit Test Runner Y Y
Localization N Y
MVC Pattern N Y
Template N Y
Two-way Binding N Y
One-way Binding N Y
Dependency Injection N Y
Routing N Y
Restful API N Y

Q. What is jQLite or jQuery lite?

Ans. jQLite is a subset of jQuery that is built directly into AngularJS. jQLite provides you all the useful features of jQuery. In fact it provides you limited features or functions of jQuery.

Here is a table of supported jQuery methods by jQLite.

jQuery Method Limitation, if any
addClass()
after()
append()
attr()
bind() Does not support namespace, selectors and eventData
Children Does not support selectors
clone()
contents()
css()
data()
detach()
empty()
eq()
find() Limited to lookups by tag name
hasClass()
html()
text() Does not support selectors
on() Does not support namespace, selectors and eventData
off() Does not support namespace, selectors
one() Does not support namespace, selectors
parent() Does not support selectors
prepend()
Prop
ready()
Remove
removeAttr()
removeClass()
removeData()
replaceWith()
toggleClass()
triggerHandler() Passes a dummy event object to handlers
unbind() Does not support namespace
val()
wrap()

Q. Is AngularJS a library, framework, plugin or a browser extension?

Ans. AngularJS is a first class JavaScript framework which allows you to build well structured, easily testable, and maintainable front-end applications. It is not a library since library provides you limited functionality or has dependencies to other libraries.

It is not a plugin or browser extension since it is based on JavaScript and compatible with both desktop and mobile browsers.

Q. What browsers AngularJS support?

Ans.The latest version of AngularJS 1.3 support Safari, Chrome, Firefox, Opera 15+, IE9+ and mobile browsers (Android, Chrome Mobile, iOS Safari, Opera Mobile).

AngularJS 1.3 has dropped support for IE8 but AngularJS 1.2 will continue to support IE8.

Q. What is the size of angular.js file?

Ans. The size of the compressed and minified file is < 36KB. Q. What are AngularJS features?

Ans. The features of AngularJS are listed below:

  1. Modules
  2. Directives
  3. Templates
  4. Scope
  5. Expressions
  6. Data Binding
  7. MVC (Model, View & Controller)
  8. Validations
  9. Filters
  10. Services
  11. Routing
  12. Dependency Injection
  13. Testing

Q. How AngularJS handle the security?

Ans. AngularJS provide following built-in protection from basic security holes:

  1. Prevent HTML injection attacks.
  2. Prevent Cross-Site-Scripting (CSS) attacks.
  3. Prevent XSRF protection for server side communication.

Also, AngularJS is designed to be compatible with other security measures like Content Security Policy (CSP), HTTPS (SSL/TLS) and server-side authentication and authorization that greatly reduce the possible attacks.

 Q. What components can be defined within AngularJS modules?

Ans. You can define following components with in your angular module:

  1. Directive
  2. Filter
  3. Controller
  4. Factory
  5. Service
  6. Provider
  7. Value
  8. Config settings and Routes

Q. What is core module in AngularJS?

Ans. ng is the core module in angular. This module is loaded by default when an angular app is started. This module provides the essential components for your angular app like directives, services/factories, filters, global APIs and testing components.

Q. How angular modules load the dependencies?

Ans. An angular module use configuration and run blocks to inject dependencies (like providers, services and constants) which get applied to the angular app during the bootstrap process.

Q. What is difference between config() and run() method in AngularJS?

Ans. Configuration block – This block is executed during the provider registration and configuration phase. Only providers and constants can be injected into configuration blocks. This block is used to inject module wise configuration settings to prevent accidental instantiation of services before they have been fully configured. This block is created using config() method.

angular.module(‘myModule’, []).

config(function (injectables) { // provider-injector

  • This is an example of config block.
  • You can have as many of these as you want.
  • You can only inject Providers (not instances)
  • into config blocks.

}).

run(function (injectables) { // instance-injector

  • This is an example of a run block.
  • You can have as many of these as you want.
  • You can only inject instances (not Providers)
  • into run blocks

});

Run block – This block is executed after the configuration block. It is used to inject instances and constants. This block is created using run() method. This method is like as main method in C or C++.

The run block is a great place to put event handlers that need to be executed at the root level for the application.

For example, authentication handlers.

Q. When dependent modules of a module are loaded?

Ans. A module might have dependencies on other modules. The dependent modules are loaded by angular before the requiring module is loaded.

In other words the configuration blocks of the dependent modules execute before the configuration blocks of the requiring module. The same is true for the run blocks. Each module can only be loaded once, even if multiple other modules require it.

Q. What is Global API?

Ans. Global API provides you global functions to perform common JavaScript tasks such as comparing objects, deep copying, iterating through objects, and converting JSON data etc. All global functions can be accessed by using the angular object. The list of global functions is given below:

Name Description
angular.lowercase Converts the specified string to lowercase.
angular.uppercase Converts the specified string to uppercase.
angular.forEach Invokes the iterator function once for each item in obj collection, which can be
either an object or an array.
angular.isUndefined Determines if a reference is undefined.
angular.isDefined Determines if a reference is defined.
angular.isObject Determines if a reference is an Object.
angular.isString Determines if a reference is a String.
angular.isNumber Determines if a reference is a Number.
angular.isDate Determines if a value is a date.
angular.isArray Determines if a reference is an Array.
angular.isFunction Determines if a reference is a Function.
angular.isElement Determines if a reference is a DOM element (or wrapped jQuery element).
angular.copy Creates a deep copy of source, which should be an object or an array.
angular.equals Determines if two objects or two values are equivalent. Supports value types,
regular expressions, arrays and objects.
angular.bind Returns a function which calls function fn bound to self
angular.toJson Serializes input into a JSON-formatted string. Properties with leading $$
characters will be stripped since angular uses this notation internally.
angular.fromJson Deserializes a JSON string.
angular.bootstrap Use this function to manually start up angular application.
angular.reloadWithDebugInfo Use this function to reload the current application with debug information turned
on.
angular.injector Creates an injector object that can be used for retrieving services as well as for
dependency injection
angular.element Wraps a raw DOM element or HTML string as a jQuery element.
angular.module Used for creating, registering and retrieving Angular modules.

Q. What is Angular Prefixes $ and $$?

Ans. To prevent accidental name collisions with your code, Angular prefixes names of public objects with $ and names of private objects with $$. So, do not use the $ or $$ prefix in your code.

Q. What are Filters in AngularJS?

Ans. Filters are used to format data before displaying it to the user. They can be used in view templates, controllers, services and directives. There are some built-in filters provided by AngularJS like as Currency, Date, Number, OrderBy, Lowercase, Uppercase etc. You can also create your own filters.

Filter Syntax

{{ expression | filter}}

Filter Example

Q. What are Expressions in AngularJS?

Ans. AngularJS expressions are much like JavaScript expressions, placed inside HTML templates by using double braces such as: {{expression}}. AngularJS evaluates expressions and then dynamically adds the result to a web page. Like JavaScript expressions, they can contain literals, operators, and variables.

There are some valid AngularJS expressions:

  • {{ 1 + 2 }}
  • {{ x + y }}
  • {{ x == y }}
  • {{ x = 2 }}
  • {{ user.Id }}

Q. How AngularJS expressions are different from the JavaScript expressions?

Ans. AngularJS expressions are much like JavaScript expressions but they are different from JavaScript expressions in the following ways:

  1. Angular expressions can be added inside the HTML templates.
  2. Angular expressions doesn’t support control flow statements (conditionals, loops, or exceptions).
  3. Angular expressions support filters to format data before displaying it.

Q. What are Directives in AngularJS?

Ans. AngularJS directives are a combination of AngularJS template markups (HTML attributes or elements, or CSS classes) and supporting JavaScript code. The JavaScript directive code defines the template data and behaviors of the HTML elements.

AngularJS directives are used to extend the HTML vocabulary i.e. they decorate html elements with new behaviors and help to manipulate html elements attributes in interesting way.

There are some built-in directives provided by AngularJS like as ng-app, ng-controller, ng-repeat, ng-model etc.

Q. What is the role of ng-app, ng-init and ng-model directives?

Ans. The main role of these directives is explained as:

  • ng-app – Initialize the angular app.
  • ng-init – Initialize the angular app data.
  • ng-model – Bind the html elements like input, select, text area to angular app model.

Q. How to create custom directives in AngularJS?

Ans. You can create your own custom directive by using following syntax:

var app = angular.module(‘app’, []);

//creating custom directive syntax

app.directive(“myDir”, function () {

return {

restrict: “E”, //define directive type like E = element, A = attribute, C = class, M = comment

scope: { //create a new child scope or an isolate scope

title: ‘@’ //@ reads the attribute value,

//= provides two-way binding,

//& works with functions

},

template: “

{{ myName }}

“,// define HTML markup

templateUrl: ‘mytemplate.html’, //path to the template, used by the directive

replace: true | false, // replace original markup with template yes/no

transclude: true | false, // copy original HTML content yes/no

controller: function (scope) { //define controller, associated with the directive template

//TODO:

},

link: function (scope, element, attrs, controller) {//define function, used for DOM manipulation

//TODO:

}

}

});

Q. What are different ways to invoke a directive?

Ans. There are four methods to invoke a directive in your angular app which are equivalent.

Method Syntax
As an attribute
As a class
As an element
As a comment

Q. What is restrict option in directive?

Ans. The restrict option in angular directive, is used to specify how a directive will be invoked in your angular app i.e. as an attribute, class, element or comment.

There are four valid options for restrict:

‘A’ (Attribute)-

‘C’ (Class)- ‘E’ (Element)-

‘M’ (Comment)-

Q. Can you define multiple restrict options on a directive?

Ans. You can also specify multiple restrict options to support more than one methods of directive invocation as an element or an attribute. Make sure all are specified in the restrict keyword as:

restrict: ‘EA’

Q. What is auto bootstrap process in AngularJS?

OR

How AngularJS is initialized automatically?

Ans. Angular initializes automatically upon DOMContentLoaded event or when the angular.js script is downloaded to the browser and the document.readyState is set to complete. At this point AngularJS looks for the

ng-app directive which is the root of angular app compilation and tells about AngularJS part within DOM. When the ng-app directive is found then Angular will:

  1. Load the module associated with the directive.
  2. Create the application injector.
  3. Compile the DOM starting from the ng-approot element.

This process is called auto-bootstrapping.

Example

Hello {{msg}}!

Q. What is manual bootstrap process in AngularJS?

OR

How AngularJS is initialized manually?

Ans. You can manually initialized your angular app by using angular.bootstrap() function. This function takes the modules as parameters and should be called within angular.element(document).ready() function. The angular.element(document).ready() function is fired when the DOM is ready for manipulation.

Example

Hello {{msg}}!

‘undefined’=== typeof _trfq || (window._trfq = []);’undefined’=== typeof _trfd && (window._trfd=[]),_trfd.push({‘tccl.baseHost’:’secureserver.net’}),_trfd.push({‘ap’:’cpsh’},{‘server’:’p3plcpnl0783′}) // Monitoring performance to make your website faster. If you want to opt-out, please contact web hosting support.

Note

  • You should not use the ng-appdirective when manually bootstrapping your app.
  • You should not mix up the automatic and manual way of bootstrapping your app.
  • Define modules, controller, services etc. before manually bootstrapping your app as defined in above example.

Q. How to bootstrap your angular app for multiple modules?

Ans. AngularJS is automatically initialized for one module. But sometimes, it is required to bootstrap for multiple modules and it can be achieved by using two methods:

  1. Automatic bootstrap (by combining multiple modules into one module) – You can combine multiple modules into single modules and your angular app will be automatically initialized for newly created module and other modules will act as dependent modules for newly created module.

For example, suppose you have two modules: module1 and model2, and you have to initialize your app automatically based on these two modules then you achieve this following way:

MULTIPLE MODULES BOOTSTRAP

{{name}}

{{name}}

  1. Manual bootstrap – You can manually bootstrap your app by using bootstrap()function, for multiple modules.

The above example can be rewritten as for manual bootstrap process as given below:

MULTIPLE MODULES BOOTSTRAP

{{name}}

{{name}}

{{name}}

Q. What is scope in AngularJS?

Ans. Scope is a JavaScript object that refers to the application model. It acts as a context for evaluating angular expressions. Basically, it acts as glue between controller and view.

Scopes are hierarchical in nature and follow the DOM structure of your AngularJS app. AngularJS has two scope objects: $rootScope and $scope.

Q. What is scope hierarchy?

OR

What is scope inheritance?

Ans. The $scope object used by views in AngularJS are organized into a hierarchy. There is a root scope, and the $rootScope can has one or more child scopes. Each controller has its own $scope (which is a child of the $rootScope), so whatever variables you create on $scope within controller, these variables are accessible by the view based on this controller.

For example, suppose you have two controllers: ParentController and ChildController as given below:

Manager Name {{managerName}}
Company Name {{companyName}}
Team Lead Name {{ teamLeadName }}
Reporting To {{managerName}}
Company Name {{companyName}}
Child Controller
Parent Controller

Output

Q. What is the difference between $scope and scope?

Ans. The module factory methods like controller, directive, factory, filter, service, animationconfig and run receive arguments through dependency injection (DI). In case of DI, you inject the scope object with the dollar prefix i.e. $scope. The reason is the injected arguments must match to the names of injectable objects followed by dollar ($) prefix.

For example, you can inject the scope and element objects into a controller as given below:

module.controller(‘MyController’, function ($scope, $element) { // injected arguments });

When the methods like directive linker function don’t receive arguments through dependency injection, you just pass the scope object without using dollar prefix i.e. scope. The reason is the passing arguments are received by its caller.

module.directive(‘myDirective’, function () // injected arguments here {

return {

  • linker function does not use dependency injection link: function (scope, el, attrs) {
  • the calling function will passes the three arguments to the linker: scope, element and attributes, in the same order

}

};

});

In the case of non-dependency injected arguments, you can give the name of injected objects as you wish. The above code can be re-written as:

module.directive(“myDirective”, function () {

return {

link: function (s, e, a) {

  • s == scope
  • e == element
  • a == attributes

}

};

});

In short, in case of DI the scope object is received as $scope while in case of non-DI scope object is received as scope or with any name.

Q. How AngularJS is compiled?

Ans. Angular’s HTML compiler allows you to teach the browser new HTML syntax. The compiler allows you to attach new behaviors or attributes to any HTML element. Angular calls these behaviors as directives.

AngularJS compilation process takes place in the web browser; no server side or pre-compilation step is involved. Angular uses $compiler service to compile your angular HTML page. The angular’ compilation process begins after your HTML page (static DOM) is fully loaded. It happens in two phases:

  1. Compile – It traverse the DOM and collect all of the directives. The result is a linking function.
  2. Link – It combines the directives with a scope and produces a live view. Any changes in the scope model are reflected in the view, and any user interactions with the view are reflected in the scope model.

The concept of compile and link comes from C language, where you first compile the code and then link it to actually execute it. The process is very much similar in AngularJS as well.

Q. How AngularJS compilation is different from other JavaScript frameworks?

Ans. If you have worked on templates in other java script framework/library like backbone and jQuery, they process the template as a string and result as a string. You have to dumped this result string into the DOM where you wanted it with innerHTML()

AngularJS process the template in another way. It directly works on HTML DOM rather than strings and manipulates it as required. It uses two way data-binding between model and view to sync your data.

Q. What directives are used to show and hide HTML elements in AngularJS?

Ans. ng-show and ng-hide directives are used to show and hide HTML elements in the AngularJS based on an expression. When the expression is true for ng-show or ng-hide, HTML element(s) are shown or hidden from the page. When the expression is false for ng-show or ng-hide, HTML element(s) are hidden or shown on the page.

ng-show Visible

ng-hide Invisible

Q. Explain directives ng-if, ng-switch and ng-repeat?

Ans. ng-if – This directive can add / remove HTML elements from the DOM based on an expression. If the expression is true, it add HTML elements to DOM, otherwise HTML elements are removed from the DOM.

ng-if Visible

ng-switch – This directive can add / remove HTML elements from the DOM conditionally based on scope expression.

Shown when case is 1

Shown when case is 2

Shown when case is anything else than 1 and 2

ng-repeat – This directive is used to iterate over a collection of items and generate HTML from it.

  • {{ name}}

Q. What are ng-repeat special variables?

Ans. The ng-repeat directive has a set of special variables which you are useful while iterating the collection.

These variables are as follows:

  • $index
  • $first
  • $middle
  • $last
  • [{{$index + 1}}{{name}}is a {{friend.gender}}.

(first element found)

(middle element found)

(last element found)

Output

The $index contains the index of the element being iterated. The $first, $middle and $last returns a boolean value depending on whether the current item is the first, middle or last element in the collection being iterated.

Q. What is ng-include and when to use it?

Ans. ng-include is a directive which is used to include external HTML fragments from other files into the view’s HTML template.

For exampleindex.html file can be added inside the div element by using ng-include directive as an attribute.

ng-include directive is limited to load HTML fragments file from same domain but it doesn’t work for cross-domain i.e. it can’t load the HTML fragments file from different domains.

 Q. What angular components can be defined within AngularJS templates?

Ans. AngularJS templates can have following angular elements and attributes:

  1. Directive
  2. Angular Markup (‘{{}}’)
  3. Filters
  4. Form Controls

Q. What is data binding in AngularJS?

Ans. AngularJS data-binding is the most useful feature which saves you from writing boilerplate code (i.e. the sections of code which is included in many places with little or no alteration). Now, developers are not responsible for manually manipulating the DOM elements and attributes to reflect model changes. AngularJS provides two-way data-binding to handle the synchronization of data between model and view.

Q. What is issue with two-way data binding?

OR

Why one-way data binding is introduced?

Ans. In order to make data-binding possible, Angular uses $watch APIs to observe model changes on the scope. Angular registered watchers for each variable on scope to observe the change in its value. If the value, of variable on scope is changed then the view gets updated automatically.

This automatic change happens because of $digest cycle is triggered. Hence, Angular processes all registered watchers on the current scope and its children and checks for model changes and calls dedicated watch listeners until the model is stabilized and no more listeners are fired. Once the $digest loop finishes the execution, the browser re-renders the DOM and reflects the changes.

By default, every variable on a scope is observed by the angular. In this way, unnecessary variable are also observed by the angular that is time consuming and as a result page is becoming slow.

Hence to avoid unnecessary observing of variables on scope object, angular introduced one-way data binding.

Angular JS Online Training

Angular JS interview questions Tags

Angular JS interview questions and answers,Angular JS online training, Angular JS interview questions, Angular JS training online, Angular JS training, Angular JS training institute, latest Angular JS interview questions, best Angular JS interview questions 2019, top 100 Angular JS interview questions,sample Angular JS interview questions,Angular JS interview questions technical, best Angular JS interview tips, best Angular JS interview basics, Angular JS Interview techniques,Angular JS Interview Tips.

For  online training videos