Angularjs Interview Questions and Answers

1) What is Angular.js?
AngularJS is a javascript framework used for creating single web page applications. It allows
you to use HTML as your template language and enables you to extend HTML’s syntax to
express your application’s components clearly
2) Explain what are the key features of Angular.js ?
The key features of angular.js are
● Scope
● Controller
● Model
● View
● Services
● Data Binding
● Directives
● Filters
● Testable
3) 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.
4) Explain what is services 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, filters and so on.
5) Explain what is Angular Expression? Explain 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
● Context : In Angular, the expressions are evaluated against a scope object, while
the Javascript expressions are evaluated against the global window
● Forgiving: In Angular expression evaluation is forgiving to null and undefined,
while in Javascript undefined properties generates TypeError or ReferenceError
● No Control Flow Statements: Loops, conditionals or exceptions cannot be used in
an angular expression
● Filters: To format data before displaying it you can use filters
6) 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 nginit
directive
● <div ngcontroller
= “ apps/dashboard/account ” ngswitch
● On = “! ! accounts” nginit
= “ loadData ( ) ”>
7) Explain what are directives ? Mention some of the most commonly used directives in
Angular.js application ?
A directive is something that introduces new syntax, they are like markers on DOM element
which attaches a special behavior to it. In any Angular.js application, directives are the most
important components.
Some of the commonly used directives are ngmodel,
ngApp,
ngbind,
ngrepeat
,
ngshow
etc.
8) Mention what are the advantages of using Angular.js ?
Angular.js has several advantages in web development.
● Angular.js supports MVS pattern
● Can do two ways data binding using Angular.js
● It has perdefined
form validations
● It supports both client server communication
● It supports animations
9) Explain what Angular JS routes does ?
Angular js routes enable you to create different URLs for different content in your application.
Different URLs for different content enables user to bookmark URLs to specific content. Each
such bookmarkable URL in Angular.js is called a route
A value in Angular JS is a simple object. It can be a number, string or JavaScript object.
Values are typically used as configuration injected into factories, services or controllers. A
value should be belong to an Angular.js module.
Injecting a value into an Angular.js controller function is done by adding a parameter with the
same name as the value
10) Explain what is data binding in Angular.js ?
Automatic synchronization of data between the model and view components is referred as
data binding in Angular.js. There are two ways for data binding
1. Data mining in classical template systems
2. Data binding in angular templates
11) What makes angular.js better ?
● Registering Callbacks: There is no need to register callbacks . This makes your
code simple and easy to debug.
● Control HTML DOM programmatically: All the application that are created using
Angular never have to manipulate the DOM although it can be done if it is required
● Transfer data to and from the UI: Angular.js helps to eliminate almost all of the
boiler plate like validating the form, displaying validation errors, returning to an
internal model and so on which occurs due to flow of marshalling data
● No initilization code: With angular.js you can bootstrap your app easily using
services, which autoinjected
into your application in Guice like dependency
injection style
12) Explain what is string interpolation in angular.js ?
In angular.js the compiler during the compilation process matches text and attributes using
interpolate service to see if they contains embedded expressions. As part of normal digest
cycle these expressions are updated and registered as watches.
13) Mention the steps for the compilation process of HTML happens?
Compilation of HTML process occurs in following ways
● Using the standard browser API, first the HTML is parsed into DOM
● By using the call to the $compile () method, compilation of the DOM is performed.
The method traverses the DOM and matches the directives.
● Link the template with scope by calling the linking function returned from the
previous step
14) Explain what is directive and Mention what are the different types of Directive?
During compilation process when specific HTML constructs are encountered a behaviour 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
● Element directives
● Attribute directives
● CSS class directives
● Comment directives
15) Explain what is linking function and type of linking function?
Link combines the directives with a scope and produce a live view. For registering DOM
listeners as well as updating the DOM, link function is responsible. After the template is
cloned it is executed.
● Prelinking
function: Prelinking
function is executed before the child elements are
linked. It is not considered as the safe way for DOM transformation.
● Post linking function: Post linking function is executed after the child elements are
linked. It is safe to do DOM transformation by postlinking
function
16) Explain what is injector?
An injector is a service locator. It is used to retrieve object instances as defined by provider,
instantiate types, invoke methods and load modules. There is a single injector per Angular
application, it helps to look up an object instance by its name.
17) Explain what is the difference between link and compile in angular.js?
● Compile function: It is used for template DOM Manipulation and collect all of the
directives.
● Link function: It is used for registering DOM listeners as well as instance DOM
manipulation. It is executed once the template has been cloned.
18) 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.
19) Mention what are the styling form that ngModel adds to CSS classes ?
ngModel adds these CSS classes to allow styling of form as well as control
● ngvalid
● nginvalid
● ngpristine
● ngdirty
20) Mention what are the characteristics of “Scope”?
● To observer model mutations scopes provide APIs ($watch)
● To propagate any model changes through the system into the view from outside of
the Angular realm
● A scope inherits properties from its parent scope, while providing access to shared
model properties, scopes can be nested to isolate application components
● Scope provides context against which expressions are evaluated
21) Explain what is DI (Dependency Injection ) and how an object or function can get a
hold of its dependencies ?
DI or Dependency Injection is a software design pattern that deals with how code gets hold of
its dependencies. In order to retrieve elements of the application which is required to be
configured when module gets loaded , the operation “config” uses dependency injection.
These are the ways that object uses to hold of its dependencies
● Typically using the new operator, dependency can be created
● By referring to a global variable, dependency can be looked up
● Dependency can be passed into where it is required
22) Mention what are the advantages of using Angular.js framework ?
Advantages of using Angular.js as framework are
● Supports two way databinding
● Supports MVC pattern
● Support static template and angular template
● Can add custom directive
● Supports REST full services
● Supports form validations
● Support both client and server communication
● Support dependency injection
● Applying Animations
● Event Handlers
23) Explain the concept of scope hierarchy? How many scope can an application
have?
Each angular application consist 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 a children of their parent
scope. Similar to DOM, they also creates a hierarchical structure.
24) Explain what is the difference between angular.js and backbone.js?
Angular.js combines the functionalities of most of the 3rd party libraries, it supports individual
functionalities required to develop HTML5 Apps. While Backbone.js do their jobs individually.
25) Who created Angular JS ?
Intially it was developed by Misko Hevery and Adam Abrons. Currently it is being developed
by Google.

Advertisements

Object Oriented Javascript

Object-Oriented Javascript:

JavaScript is object-oriented to its core, with powerful, flexible OOP capabilities.

Terminology

Namespace
A container which allows developers to bundle all functionality under a unique, application-specific name.
Class
Defines the characteristics of the object. It is a template definition of variables and methods of an object.
Object
An Instance of a class.
Property
An object characteristic, such as color.
Method
An object capability, such as walk. It is a subroutine or function associated with a class.
Constructor
A method called at the moment of instantiation of an object. It usually has the same name as that of the class containing it.
Inheritance
A class can inherit characteristics from another class.
Encapsulation
A method of bundling the data and methods that use them together.
Abstraction
The conjunction of complex inheritance, methods, properties of an object must be able to simulate a reality model.
Polymorphism
Poly means “many”  and morphism means “forms“. Different classes might define the same method or property.

Prototype-based programming

Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is accomplished through a process of decorating existing objects which serve as prototypes. This model is also known as class-less, prototype-oriented, or instance-based programming.

Namespace

A namespace is a container which allows developers to bundle up all functionality under a unique, application-specific name. In JavaScript a namespace is just another object containing methods, properties and objects.

The idea behind creating a namespace in JavaScript is simple: one global object is created and all variables, methods and functions become properties of that object. Use of namespaces also minimizes the possibility of name conflicts in an application.

Let’s create a global object called MYAPP:

// global namespace
var MYAPP = MYAPP || {};

Here in above code sample we have first checked whether MYAPP is already defined (either in same file or in another file). If yes, then use the existing MYAPP global object, otherwise create an empty object called MYAPP which will encapsulate method, functions, variables and objects.

We can also create sub-namespaces:

// sub namespace
MYAPP.event = {};

The class

JavaScript is a prototype-based language which contains no class statement, such as is found in C++ or Java. This is sometimes confusing for programmers accustomed to languages with a class statement. Instead, JavaScript uses functions as classes. Defining a class is as easy as defining a function. In the example below we define a new class called Person.

function Person() { } 
or 
var Person = function(){ }

The object (class instance)

To create a new instance of an object obj we use the statement new obj, assigning the result (which is of type obj) to a variable to access it later.

In the example below we define a class named Person and we create two instances (person1and person2).

function Person() { }
var person1 = new Person();
var person2 = new Person();

The constructor

The constructor is called at the moment of instantiation (the moment when the object instance is created). The constructor is a method of the class. In JavaScript, the function serves as the constructor of the object therefore, there is no need to explicitly define a constructor method. Every action declared in the class gets executed at the time of instantiation.

The property (object attribute)

Properties are variables contained in the class; every instance of the object has those properties. Properties should be set in the prototype property of the class (function) so that inheritance works correctly.

In the example below we define the firstName property for the Person class and we define it at instantiation.

function Person(firstName) {
  this.firstName = firstName;
  console.log('Person instantiated');
}

var person1 = new Person('Alice');
var person2 = new Person('Bob');

// Show the firstName properties of the objects
console.log('person1 is ' + person1.firstName); // logs "person1 is Alice"
console.log('person2 is ' + person2.firstName); // logs "person2 is Bob"



			
		

Bootstrap Tutorial

Bootstrap:
Bootstrap is a free collection of tools for creating websites and web applications in responsive web design using this css framework which supports mobiles,tablets and desktops.

Note: Before you include bootstrap.min.js, you should even include jquery. Without jquery bootstrap wont work as many of components of bootstrap are dependent on jquery. Hence have like below for sure..

<script src=”bootstrap/js/jquery-1.11.1.min.js”></script>
<script src=”bootstrap/js/bootstrap.min.js”></script>

Mandatory add meta tag for viewport which enables support for mobiles and tablets. Like <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>.

Wanna see the difference between responsive and non responsive design??

Just open the two following links in different tabs first..

1. http://getbootstrap.com/examples/non-responsive/

2. http://livedemo00.template-help.com/wt_51334/index.html

Now click restore down as shown below..

26-09-2014 11-07-41

Now drag it to left and right to see the difference between responsive and non responsive websites.

26-09-2014 11-09-13

Use .container for a responsive fixed width container.Use .container-fluid for a full width container, spanning the entire width of your viewport.

Creating layouts:

Grid systems are used for creating page layouts through a series of rows and columns that house your content. Here’s how the Bootstrap grid system works:

  • Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding.
  • Use rows to create horizontal groups of columns.
  • Content should be placed within columns, and only columns may be immediate children of rows.
  • Predefined grid classes like .row and .col-xs-4 are available for quickly making grid layouts. Less mixins can also be used for more semantic layouts.
  • Columns create gutters (gaps between column content) via padding. That padding is offset in rows for the first and last column via negative margin on .rows.
  • The negative margin is why the examples below are outdented. It’s so that content within grid columns is lined up with non-grid content.
  • Grid columns are created by specifying the number of twelve available columns you wish to span. For example, three equal columns would use three .col-xs-4.
  • If more than 12 columns are placed within a single row, each group of extra columns will, as one unit, wrap onto a new line.
  • Grid classes apply to devices with screen widths greater than or equal to the breakpoint sizes, and override grid classes targeted at smaller devices. Therefore, applying any .col-md- class to an element will not only affect its styling on medium devices but also on large devices if a .col-lg- class is not present.
Extra small devicesPhones (<768px) Small devices Tablets (≥768px) Medium devices Desktops (≥992px) Large devices Desktops (≥1200px)
Grid behavior Horizontal at all times Collapsed to start, horizontal above breakpoints
Container width None (auto) 750px 970px 1170px
Class prefix .col-xs- .col-sm- .col-md- .col-lg-
# of columns 12

26-09-2014 11-19-37

From the above image i hope you can understand that default page width/container will be divided in to 12 cols. We can either use col-xs/col-sm/col-md/col-lg to divide columns. Here we consider col-md in dividing. If we want 12 cols in a row, you should have class row where inside you shud have col-md-1 for 12 times. Similarly if you need 3 cols have col-md-4,for 2 cols have col-md-6 and 1 column col-md-12.

Eg:

<div class="row">
  <div class="col-md-6">.col-md-6</div>
  <div class="col-md-6">.col-md-6</div>
</div>

If you want to have this grid options for all mobiles,tablets and desktops..

<div class="row">
  <div class="col-xs-12 col-sm-6 col-md-8">.col-xs-12 .col-sm-6 .col-md-8</div>
  <div class="col-xs-6 col-md-4">.col-xs-6 .col-md-4</div>
</div>

With the four tiers of grids available you’re bound to run into issues where, at certain breakpoints, your columns don’t clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix

26-09-2014 12-16-09

For the above image if we use clearfix all column grid heights will be appeared to be same.

Nesting columns

To nest your content with the default grid, add a new .row and set of .col-sm-* columns within an existing .col-sm-* column. Nested rows should include a set of columns that add up to 12 or less (it is not required that you use all 12 available columns).

<div class="row">
  <div class="col-sm-9">
    Level 1: .col-sm-9
    <div class="row">
      <div class="col-xs-8 col-sm-6">
        Level 2: .col-xs-8 .col-sm-6
      </div>
      <div class="col-xs-4 col-sm-6">
        Level 2: .col-xs-4 .col-sm-6
      </div>
    </div>
  </div>
</div>

26-09-2014 12-20-20

Column ordering

Easily change the order of our built-in grid columns with .col-md-push-* and .col-md-pull-* modifier classes.

<div class="row">
  <div class="col-md-9 col-md-push-3">.col-md-9 .col-md-push-3</div>
  <div class="col-md-3 col-md-pull-9">.col-md-3 .col-md-pull-9</div>
</div>
26-09-2014 12-22-16

Body copy

Bootstrap’s global default font-size is 14px, with a line-height of 1.428. This is applied to the <body> and all paragraphs. In addition, <p> (paragraphs) receive a bottom margin of half their computed line-height (10px by default).

Lead body copy

Make a paragraph stand out by adding .lead.

Inline text elements

For highlighting a run of text due to its relevance in another context, use the <mark> tag. – Market text

For indicating blocks of text that have been deleted use the <del> tag. – Deleted text

For indicating blocks of text that are no longer relevant use the <s> tag. – Strikethrough text

For indicating additions to the document use the <ins> tag. – Inserted text

To underline text use the <u> tag. – Underline text

For de-emphasizing inline or blocks of text, use the <small> tag to set text at 85% the size of the parent. Heading elements receive their own font-size for nested <small> elements.

You may alternatively use an inline element with .small in place of any <small>.

For emphasizing a snippet of text with a heavier font-weight. <strong>tag for bold

For emphasizing a snippet of text with italics. <em> for italics

Alignments of text:

<p class="text-left">Left aligned text.</p>
<p class="text-center">Center aligned text.</p>
<p class="text-right">Right aligned text.</p>
<p class="text-justify">Justified text.</p>
<p class="text-nowrap">No wrap text.</p>

Tables: For basic styling—light padding and only horizontal dividers—add the base class .table to any <table>.

<table class="table">
  ...
</table>
Use .table-striped to add zebra-striping to any table row within the <tbody>.
<table class="table table-striped">
  ...
</table>

Add .table-bordered for borders on all sides of the table and cells.

Add .table-hover to enable a hover state on table rows within a <tbody>.

Add .table-condensed to make tables more compact by cutting cell padding in half.

.active Applies the hover color to a particular row or cell
.success Indicates a successful or positive action
.info Indicates a neutral informative change or action
.warning Indicates a warning that might need attention
.danger Indicates a dangerous or potentially negative action

success-green,info-blue,warning-orange,danger-red

Responsive tables

Create responsive tables by wrapping any .table in .table-responsive to make them scroll horizontally on small devices (under 768px). When viewing on anything larger than 768px wide, you will not see any difference in these tables.

Forms

Individual form controls automatically receive some global styling. All textual <input>, <textarea>, and <select> elements with.form-control are set to width: 100%; by default. Wrap labels and controls in .form-group for optimum spacing.

Add .form-inline to your <form> for left-aligned and inline-block controls.

<input type="text" class="form-control" placeholder="Text input">
<div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn btn-default">Sign in</button>
    </div>
  </div>

Difference between disabled and readonly: 26-09-2014 12-44-39

<button type="button" class="btn btn-default">Default</button>
btn btn-success,
btn btn-info,
btn btn-warning,
btn btn-danger

Responsive images
Images in Bootstrap 3 can be made responsive-friendly via the addition of the .img-responsive class. This applies max-width: 100%; and height: auto; to the image so that it scales nicely to the parent element.

<img src="..." class="img-responsive" alt="Responsive image">
<img src="..." alt="..." class="img-rounded">
<img src="..." alt="..." class="img-circle">
<img src="..." alt="..." class="img-thumbnail">

Components

Over a dozen reusable components built to provide iconography, dropdowns, input groups, navigation, alerts, and much more.