Angularjs Interview Questions: Angular Js
Angularjs Interview Questions: Angular Js
codespaghetti.com/angularjs-interview-questions/
Angular JS
Angular JS Interview Questions, Best AngularJS Programs and Examples to help you ace
your next Job interview.
Table of Contents:
1/23
CHAPTER 6: Angular JS Directive Questions
Importance of AngularJS
AngularJS is a very popular framework among developers. Small to large companies are
using angularJS. If your going for an interview as a front end developers then get ready to
answer angular JS questions.
In this guide i have collected and curated the best angularJS interview questions. Go
through these questions and you will increase your chances of success in interviews.
Before we dive deep into this guide. Let's see what are the top 5 questions asked in
angularJS interviews
Top 5 AngularJS Interview Questions
What is Angular Js
AngularJS is a structural framework for dynamic web apps. It lets you use HTML as
your template language and lets you extend HTML's syntax to express your
application's components clearly.
AngularJS's data binding and dependency injection eliminate much of the code you
would otherwise have to write. And it all happens within the browser, making it an
ideal partner with any server technology.
AngularJS provides developers options to write client side application (using
JavaScript) in a clean MVC way.
Application written in AngularJS is cross-browser compliant. AngularJS automatically
handles JavaScript code suitable for each browser.
Scope – Object representing the model, acts as a glue layer between controller and view.
Services – Substitutable objects that are wired together using dependency injection. e.g.
$location service.
3/23
Filters – Formats the value of an expression for displaying to the user. e.g., uppercase,
lowercase.
Directives – These are extended HTML attributes start with the “ng-” prefix. e.g., ng-app
directive used to initialize the angular app.
Model – Represents data, could be static data from a JSON file or dynamic data from
a database.
View – Renders data for the user.
Controller – Gives control over the model and view for collating information to the
user.
Deep linking – Enables the encoding of the application state in the URL and vice versa.
Dependency injection – A design pattern to let the components injected into each other
as dependencies
During every digest cycle, all new scope model values are compared against the previous
values. This is called dirty checking. If change is detected, watches set on the new model
are fired and another digest cycle executes. This goes on until all models are stable.
The digest cycle is triggered automatically but it can be called manually using “.$apply()”.
Whenever a web page loads in the browser, following steps execute in the background.
First, the HTML file containing the code gets loaded into the browser. After that, the
JavaScript file mentioned in the HTML code gets loaded. It then creates a global
object for angular. Now, the JavaScript which displays the controller functions gets
executed.
In this step, AngularJS browses the complete HTML code to locate the views. If the
same is available, then Angular links it to the corresponding controller function.
In this step, AngularJS initiates the execution of required controller functions. Next, it
populates the views with data from the model identified by the controller. With this the
page is ready.
AngularJS enriches form filling and validation. We can use $dirty and $invalid flags to do
the validations in seamless way. Use novalidate with a form declaration to disable any
browser specific validation.
Question:
5/23
Scopes are controllers specific. If we define nested controllers then child controller will
inherit the scope of its parent controller.
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
mainApp.controller("circleController", function($scope) {
$scope.message = "In circle controller";
});
provider is used by AngularJS internally to create services, factory etc. during config
phase(phase during which AngularJS bootstraps itself).
Below mention script can be used to create MathService that we've created earlier.
Provider is a special factory method with a method get() which is used to return the
value/service/factory.
//define a module
var mainApp = angular.module("mainApp", []);
...
//create a service using provider which defines a method square to return square of
a number.
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
An AngularJS Filter changes or transforms the data before passing it to the view. These
Filters work in combination with AngularJS expressions or directives. AngularJS uses pipe
character (“|”) to add filters to the expressions or directives. For example:
6/23
<p> {{ bid | currency }} </p>
The above example is an expression enclosed in the curly braces. The filter used in this
expression is currency. Also important to note that filters are case-sensitive. AngularJS
provides following filters to transform data.
The elements are selected, either from the beginning or the end of the source array or
string. This depends on the value and sign (positive or negative) of the limit.
It also supports a comparator function where we can define what will be counted as a
match or not.
Compile – It collects an HTML string or DOM into a template and creates a template
function. It can then be used to link the scope and the template together.
AngularJS uses the compile function to change the original DOM before creating its
instance and before the creation of scope. Before discussing the Pre-Link and the Post-Link
functions let’s see the Link function in detail.
Link – It has the duty of linking the model to the available templates. AngularJS does the
data binding to the compiled templates using Link. Following is the Link syntax.
Scope – It is the scope of the directive. element – It is the DOM element where the directive
has to be applied.
AngularJS allows setting the link property to an object also. The advantage of having an
object is that we can split the link function into two separate methods called, pre-link and
post-link.
Post-Link – Execution of Post-Link function starts after the linking of child elements. It is
safer to do DOM transformation during its execution. The post-link function is suitable to
execute the logic.
Pre-Link – It gets executed before the child elements are linked. It is not safe to do DOM
transformation. As the compiler linking function will fail to locate the correct elements.
It is good to use the pre-link function to implement the logic that runs when AngularJS has
already compiled the child elements. Also, before any of the child element’s post-link
functions have been called.
Understanding the life cycle of an AngularJS application makes it easier to learn ,design
and implement the code. AngularJS App life cycle consists of following three phases
These three phases of the life cycle occur each time a web page of an AngularJS
application gets loaded into the browser. Let’s learn about each of the three stages in
detail:
The Bootstrap Phase – In this phase, the browser downloads the AngularJS javascript
library. .
The Compilation Phase – The second phase of the AngularJS life cycle is the HTML
compilation stage. Initially, when a web page loads in the browser, a static form of the DOM
gets loaded.
During the compilation phase, this static DOM gets replaced with a dynamic DOM which
represents the app view.
There are two main steps – first, is traversing the static DOM and collecting all the
directives.
These directives are now linked to the appropriate JavaScript functionality which lies either
in the AngularJS built-in library or custom directive code. The combination of directives and
the scope, produce the dynamic or live view.
The Runtime Data Binding Phase – This is the final phase of the AngularJS application. It
remains until the user reloads or navigates to a different web page.
At this point, any changes in the scope get reflected in the view, and any changes in the
view are directly updated in the scope, making the scope the single source of data for the
8/23
view.
This shows that AngularJS behaves differently from traditional methods of binding data.
The traditional methods combine a template with data, received from the engine and then
manipulate the DOM each time there is any change in the data.
However, AngularJS compiles the DOM only once and then links the compiled template as
necessary, making it much more efficient than the traditional methods.
The link function combines the directives with a scope to produce a live view.The link
function is responsible for instance DOM manipulation and for registering DOM listeners.
The compile function is responsible for template DOM manipulation as well as the
collection of all the directives.
The first one is an AngularJS event, “$destroy”, and the second one is a jqLite / jQuery
event “$destroy”.
The first one can be used by AngularJS scopes where they are accessible, such as in
controllers or link functions.
Consider the two below happening in a directive’s postLink function. The AngularJS event:
The jqLite / jQuery event is called whenever a node is removed, which may just happen
without scope teardown.
The two officially recommended methods fare disabling debug data and enabling strict DI
mode.
9/23
myApp.config(function
($compileProvider)
{ $compileProvider.debugInfoEnabled(false);
});
That tweak disables appending scope to elements, making scopes inaccessible from the
console. The second one can be set as a directive:
The performance gain lies in the fact that the injected modules are annotated explicitly,
hence they don’t need to be discovered dynamically.
You don’t need to annotate yourself, just use some automated build tool and library for that.
Using one-time binding where possible. Those bindings are set, e.g. in “{{ ::someModel }}”
interpolations by prefixing the model with two colons.
In such a case, no watch is set and the model is ignored during digest.
which executes nearby digest calls just once, using a zero timeout.
The DOM is the Document Object Model. It’s the view part of the UI. Whatever we change
in page elements is reflected in the DOM.
BOM is the Browser Object Model, which specifies the global browser objects like window,
local storage, and console.
Controllers are simple JavaScript functions that are bound to a particular scope. They are
the prime actors in AngularJS framework and carry functions to operate on data.
As the name says they control how data flows from the server to HTML.
For example here is simple “User” controller which provides data via “UserName” and
“UserCode” property and Add/ Update logic to save the data to database.
10/23
function User($scope)
{
$scope.UserName = "Arthur";
$scope.UserCode = "2111";
$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 “User” controller via the
“ng-controller” directive and the properties are binded using “ng-model” directive.
<div ng-controller="User">
<input type=text id="UserName" ng-model="UserName"/><br />
<input type=text id="UserCode" ng-model="UserCode"/>
</div>
AngularJS expressions are unit of code. Which are used to bind application data to html.
Expressions are written inside double braces like {{ expression}}.
{{1+1}}
The below expression multiplies quantity and cost to get the total value.
<div ng-controller="UserV">
The value of Customer code is {{UserCode}}
</div>
11/23
We can use “ng-init” directive to do this. In the example below “ng-init” directive is used to
initialize the “pi” value.
“$scope” is an object instance of a controller. “$scope” object instance is created when “ng-
controller” directive is encountered.
function ScopeFunction($scope)
{
$scope.ControllerName = "ScopeFunction";
}
function TestFunction($scope)
{
$scope.ControllerName = "TestFunction";
}
Now to attach the above controllers to HTML we should use “ng-controller” directive. For
instance you can see below how “ng-controller” directive attaches “ScopeFunction” with
“div1” tag and “Testfunction” with “div2” tag.
AngualrJS Directives
12/23
Question: What Are Directives?
Directives are special markers on a DOM element that tell the html compiler to attach a
specified behavior to the DOM element. Directives start with ng-prefix. Some of the built-in
directives include ngClass, ngApp, ngRepeat, ngModel, ngBind and ngInit
Comment directives
CSS class directives
Attribute directives
Element directives
There are four different ways to invoke a directive in an angular application. They are as
follows.
1) As an attribute:
<span my-directive></span>
2) As a class:
13/23
<span class="my-directive: expression;"></span>
3) As an element:
<my-directive></my-directive>
4) As a comment:
If we want to create our own custom Angular directive and attach it with HTML elements as
shown in the below code.
To create a custom directive we need to use the “directive” function to register the directive
with angular application. When we call the “register” method of “directive” we need to
specify the function which will provide the logic for that directive.
For example in the below code we have created a copy right directive and it returns a copy
right text.
Please note “app” is an angular application object which has been explained in the previous
sections.
app.directive('companyCopyRight', function ()
{
return
{
template: '@CopyRight questpond.com '
};
});
For angular custom directive the best practice is to follow camel casing and that also with
atleast two letter’s. In camel case naming convention we start with a small letter, followed
by a capital letter for every word.
So when you register a custom directive it should be with camel case format as shown in
the below code “companyCopyRight”.
14/23
app.directive('companyCopyRight', function ()
{
return
{
template: '@CopyRight questpond.com '
};
});
https://code.tutsplus.com/tutorials/mastering-angularjs-directives--cms-22511
https://www.codeschool.com/blog/2015/03/06/digging-advanced-angularjs-directives/
https://docs.angularjs.org/guide/directive
https://github.com/huseyinbabal/mastering-angularjs-directives
https://gist.github.com/umidjons/6669708
Question: What Are The Web Application Security Risks That A Web
Developer Should Avoid While Doing Development Using AngularJS?
Following are the most critical web application development flaws that a developer should
take care of:
Injection attack.
Broken Authentication and Session Management.
Cross-Site Scripting (XSS)
15/23
Insecure direct object references.
Security Misconfiguration.
Sensitive Data Exposure.
Cross-Site Request Forgery (CSRF).
Missing Function Level Access Control.
Using components that possess vulnerabilities.
In validated redirects and forwards.
Testing AngularJS
Since Angular JS facilitates separation of client-side components with the help of inbuilt
dependency injection (DI) management.
it has testing support for every component e.g. Angular Controller, Angular Service, etc. It’s
an always good idea of testing client-side components before deployment.
Here are some frameworks which can be used for testing AngularJS applications.
This provides for clean syntax using which we can write tests. Jasmine also provides
functions for structuring the test using assertions.
This framework runs tests against the application running in a real browser.
This is a NodeJs program and uses Jasmine for its test syntax.
Karma - is a JavaScript command line tool. This tool is used to use the web
server to load the application code and test it.
AngularJS vs jQuery
Templating No Yes
Localization No Yes
WHAT IS JQUERY?
jQuery is a DOM manipulation library that makes it easier to use JavaScript on your
website. jQuery simplifies the things for developers.
It takes the complex code that would be required to make AJAX calls or manipulate the
DOM and wraps them into simple methods you can call with a single line of JavaScript.
Here are some of the key technical features that are available in the jQuery library:
HTML/DOM manipulation
CSS manipulation
Effects and animations
Cross-browser compatibility
AJAX/JSONP
Event handling
jQuery can be used in conjunction with other frameworks, including AngularJS. In fact,
AngularJS is built off of an implementation of jQuery called jqLite.
Since jQuery has no real structure, the developer has full freedom to build projects as they
see fit.
However the lack of structure also means it’s easier to fall into the trap of “spaghetti code,”
which can lead to confusion on larger projects with no clear design direction or code
maintainability. For these situations, a framework like AngularJS can be a big help.
JQuery shines when you require flexibility or see a particular feature that you wish to
include in your app, like a slider. It’s also great for quickly scripting solutions that work to
test an idea.
WHAT IS ANGULARJS?
AngularJS is a JavaScript framework that was specifically designed to help developers
build SPAs in accordance with best practices for web development.
By providing a structured environment for building SPAs, the risk of producing “spaghetti
code” is greatly reduced.
AngularJS also provides a suite of features that help the developer do more with less code
than would be required with “vanilla JavaScript” (developer speak for plain, simple
JavaScript without the use of any libraries) and jQuery.
Angular directives
Templating
Dependency injection
Two-way data binding
Support for MVC
RESTful API
Form validation
It goes without saying that AngularJS also abstracts the DOM, has a system for managing
event handlers, and supports AJAX/JSONP.
If you are looking for a full featured framework for developing web
applications from scratch.
It will also make it easier to keep your web project organized and modular to
avoid repeating code.
AngularJS vs ReactJS
18/23
React JS is a library that deals with views, AngularJS is a full fledge framework.
The primary difference between AngularJS and ReactJS lies in state management. Angular
has data-binding bundled in by default, whereas React is generally augmented by Redux to
give unidirectional data flow and work with immutable data.
Both are opposing approaches and there is no consensus on which is better: mutable/data
binding or immutable/unidirectional.
Scalability:
Angular is easy to scale thanks to its design as well as a powerful CLI. React is testable
and therefore scalable compared to other frameworks.
Dependency Injection:
Angular supports dependency injection and one great advantage is the ability to have
different life cycles for different stores.
Some of the common React paradigms deploy some kind of global app state that maps to
disparate components, however it is conducive to the introduction of bugs when cleaning
19/23
the global state on component unmount.
On the other hand, a store that is created on component mount and is seamlessly available
to the component’s children –is a more useful and often neglected concept.
This is out of the box in Angular, but quite easily replicated with MobX as well.
React is quite easy and simple to understand but it takes quite some time to set up a
project in React.
Angular on the other hand, is not simple by any means. Its inherent complexity sometimes
causes confusion and Angular specific 3rd party libraries and syntax.
Overall, both frameworks provide a robust set of tools for quality, scalable, reactive web-
based applications.
For those who prefer to code in classic JS, React may find more favors, but for those
looking at a more mature and sophisticated solution, AngularJS might be your best bet.
Angular provides a way for developers to quickly build modern web applications. Angular
was created by Google and is now operated as an open source project.
Angular JS is getting famous day by day. In order to get hired as front end developer. You
need to prepare angularJS interview questions.
20/23
Programming interviews are not easy and your only hope to survive is to prepare very
seriously.
Understand the core concepts about angularJS. What are the pros and cons of using
angularJS in your projects. And how an angularJS application can be tested.
21/23
22/23
AngularJS Interview Questions PDF
References
https://www.upwork.com/hiring/development/angularjs-vs-jquery/
https://www.airpair.com/angularjs/posts/jquery-angularjs-comparison-migration-
walkthrough
https://www.rishabhsoft.com/blog/reactjs-vs-angularjs
http://www.dotnetcurry.com/angularjs/1255/unit-testing-angularjs-using-jasmine-
karma
https://scotch.io/tutorials/testing-angularjs-with-jasmine-and-karma-part-1
23/23