In this software era doesn’t matter you are working on php,java or .net, everywhere there is demand frontend software (such as angularJS, reactJS) to make light weighted website. Below is the list of latest and updated AngularJS interview questions and their answers for freshers as well as experienced users. These interview question covers latest version of AngularJS. These interview questions will help you to prepare for the interviews.

If there is any new Angular JS interview question that have been asked to you, kindly post it in the the comment section.


 

1. What is AngularJS?

Ans:

AngularJS has been introduced by the giant, Google. It is a framework that helps you to create dynamic Web apps. Normally, AngularJS uses HTML as the backbone. AngularJS creates extended HTML tags that can be used as normal HTML tags. These tags will help you to write an efficient code. The interesting fact is that you can reduce the lines of code you may need to write when you use normal JavaScript.

AngularJS is an open-source JavaScript framework developed by Google. It is a structural framework for dynamic Web apps. It is easy to update and get information from your HTML document. It helps in writing a proper maintainable architecture, that can be tested at a client side code.
This framework is developed on MVC (Model-View-Controller) design pattern.
It provides full featured SPA (Single Page Application) framework.
It supports Dependency Injection.
It supports two-way data binding.
It provides routing features.
Testing was designed right from the beginning; so you can build robust tests.
For DOM manipulation, jqLite is built-in; which is kind of like the Mini-Me of jQuery.
Separation of the client side of an Application from the Server side.
The AngularJS framework uses Plain Old JavaScript Objects(POJO), it doesn’t need the getter or setter functions.
Using the code

Let’s start using AngularJS. What would be the first step that you need to do? That would be to include the relevant JavaScript file as in the following:

<script src="~/Script/angular.min.js"></script>

2. Explain Directives in AngularJS?

Ans:

AngularJS directives are only used to extend HTML and DOM elements’ behavior. These are the special attributes, that start with ng- prefix, that tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element.

AngularJS has a set of built-in directives like
ngBind,
ngModel
ngClass
ngApp
ngInit
ngRepeat
We can create our own directives for Angular to use them in our AngularJS Application with the controllers and services too. In this article, we’ll learn about some most important built-in directives like: ng-app, ng-init, ng-model, ng-bind and ng-repeat.

ng-app

It is the most important directive for an Angular Application, which is used to indicate starting of an Angular Application to AngularJS HTML compiler ($compile), like a “Main()” function in any compile time language like C#, Java or C++ etc. If we do not use this directive first and directly try to write other directives, it gives an error.

ng-init

ng-init directive is used to initialize an AngularJS Application data variable’s inline statement, so that we can use those in the specified block where we declare them. It is like a local member of that ng-app and it can be a value or a collection of the values and as an array, it directly supports JSON data.

ng-model

ng-model directive is used to define the model/variables value to be used in AngularJS Application’s HTML controls like <input type=’text’/> and it also provides two-way binding behavior with the model value. In some cases, it’s also used for databinding.

ng-bind

ng-bind directive is also used to bind the model/variable’s value to AngularJS Applications HTML controls as well as with HTML tags attributes like: <p/>, <span/> , and more, but it does not support two way binding. We can just see the output of the model values.

ng-repeat

ng-repeat directive is used to repeat HTML statements. Ng-repeat works the same as for each loop in C#, Java or PHP on a specific collection item like an array.

3. What are expressions in AngularJS?

Ans:

Expressions in AngularJS are just like JavaScript code snippets. JavaScript code is usually written inside double braces: {{expression}}. In other words, Angular Expressions are JavaScript code snippets with limited sub-set. Expressions are included in the HTML elements.

Like JavaScript expressions, AngularJS expressions can also have various valid expressions. We can use the operators between numbers and strings, literals, objects and arrarys inside the expression {{ }}. For example,
{{ 2 + 2 }} (numbers)
{{Name + ” ” + email}} (string)
{{ Country.Name }} (object)
{{ fact[4] }} (array)

 

4. Explain currency filter in AngularJS

Ans:

One of the filters in AngularJS is the Currency Filter. This “currency” filter includes the “$” Dollar Symbol as the default. So we can use the following code as the html template format of Currency Filter.

{{ currency_expression | currency : symbol : fractionSize}}

How to use Currency Filter in AngularJS

There are two ways by which we can use Currency Filter.
Default

If we did not provide any currency symbol then by default Dollar-Sign will be used; we can use it as follows:


Default Currency {{amount | currency}}

User Defined

To use different type of currency symbols we have to define our own symbol by using the unicode or Hexa-Decimal code of that Currency.

E.g. – For Example If we want to define Indian Currency Symbol then we have to use (Unicode-value) or (Hexa-Decimal value)
Indian Currency {{amount | currency:”&# 8377″}}

5. What is $scope in AngularJS?

Ans:

$scope in AngularJS is an object which refers to an application model. It is an object that binds view (DOM element) with the controller. In controller, model data is accessed via $scope object. As we know, AngularJS supports MV* pattern, $scope object becomes the model of MV*.

The $scope is a special JavaScript object. Both View and controller have access to the scope object. It can be used for communication between view and controller. Scope object contains both data and functions. Every AngularJS application has a $rootScope that is the top most scope created on the DOM element which contains the ng-app directive. It can watch expressions and propagate events.


Characteristics of scope object
It provides the APIs to observe model (example $watch).
It can be nested, so that it limits access to the properties. Nested scopes are either child scope or isolated scope.
It provides the APIs to propagate any model changes from the outside of “Angular realm” (example $apply).
It provides context against the expression to be evaluated.

6. What is SPA (Single page application) in AngularJS?

Ans:

Single-Page Applications (SPAs) are web applications that load a single HTML page and dynamically update that page as the user interacts with the app. SPAs use AJAX and HTML to create fluid and responsive web apps, without constant page reloads. However, this means much of the work happens on the client side, in JavaScript.

A single HTML page here means UI response page from the server. The source can be ASP, ASP.NET, ASP.NET MVC, JSP and so on.

A single-page web application, however, is delivered as one page to the browser and typically does not require the page to be reloaded as the user navigates to various parts of the application. This results in faster navigation, more efficient network transfers, and better overall performance for the end user.

Single page application in AngularJS

Single page application in AngularJS

Key Points of Single-Page Applications
The application is responsive in the UI with no page flicker
The Back/Forward buttons work as expected
More JavaScript than actual HTML
Dynamic data loading from the server-side API works with restful web service with JSON format
Rich interaction among UI components
Fewer data transfers from the server and most of the page processes in the UI occurs client-side.
The application contains tabs and subtabs with multiple HTML containers on the click of the tabs or subtabs and the specific portions of the page that are loaded into the page (the page will be one using the application)
Applications written in AngularJS are cross-browser compliant. Angular automatically handles the JavaScript code suitable for each browser.

7. How to implement routing in AngularJS?

Ans:

Routing is a core feature in AngularJS. This feature is useful in building SPA (Single Page Application) with multiple views. In SPA application, all views are different Html files and we use Routing to load different parts of the application and it’s helpful to divide the application logically and make it manageable. In other words, Routing helps us to divide our application in logical views and bind them with different controllers.

Routing in AngularJS

Routing in AngularJS

How to add routing

The$routeProvider definition contained by the module is called “ngRoute”. In app.js file, I have defined an angular app using “angular. Module” method. After creating module, we need to configure the routes. The “config” method is used to configure $routeProvider. Using “when” and “otherwise” method of $routeProvider, we can define the route for our AngularJS application.

var app = angular.module("AngularApp", ['ngRoute']); 
app.config(['$routeProvider',
function($routeProvider)
{
$routeProvider.
when('/page1',
{
templateUrl: 'Modules/Page1/page1.html',
controller: 'Page1Controller'
})
.
when('/page2',
{
templateUrl: 'Modules/Page2/page2.html',
controller: 'Page2Controller'
})
.
otherwise
({
redirectTo: '/page1'
});
}
]);

8. How many types of data binding in AngularJS?

Ans:

Data binding is a very powerful feature of the software development technologies. Data binding is the connection bridge between view and business logic (view model) of the application. Data binding in AngularJs is the automatic synchronization between the model and view. When the model changes, the view is automatically updated and vice versa. AngularJs support one-way binding as well as two-way binding.

Types of data binding in AngularJS

Types of data binding in AngularJS

Binding Directives in AngularJs
ng-bind
ng-bind-html
ng-bind-template
ng-non-bindable
ng-model
ng-bind

This directive updates the text content of the specified HTML element with the value of the given expression and the text content is changing on expression changes. It is very similar to double curly markup ( {{expression }}) but less verbose.

Syntax
</ANY ELEMENT>
Ng-bind-html

It (whatever it is) evaluates the expression and inserts the HTML content into the element in a secure way. It uses the $sanitize service, so to use this functionality, be sure that $sanitize is available.

Syntax
</ANY ELEMENT>
ng-bind-template

It (whatever it is) replaces the element text content with the interpolation of the template. It can contain multiple double curly markups.

Syntax
</ANY ELEMENT>
ng-non-bindable

This (whatever “this” is) directive informs AngularJs to not compile or bind the contents of the current DOM element This element is useful when we want to display the expression but it should not be executed by AngularJs.

Syntax

</ANY ELEMENT>

ng-model

This (whatever “this” is) directive can be bound with input, select, text area or any custom form control. It provides two-way binding. It also provides validation behavior. It also keeps the state of the control (valid/invalid, dirty/pristine, touched/untouched and so on).

Syntax

<input ng-bind=”expression”/>

9. What is a Factory method in AngularJS?

Ans:

AngularJS Factory: the purpose of Factory is also the same as Service, however in this case we create a new object and add functions as properties of this object and at the end we return this object.

Factories module.factory( ‘factoryName’, function );

10. How are validations implemented in AngularJS?

Ans:

One of the coolest features of AngularJS is client-side validation. There are so many form directives available in AngularJS. We will talk about some of them here, we will also explain custom validation. Using it you can create your own validations.

Initial requirement is reference,

Data type validation

a.In Html control use type field to specify the type of file.
b..$error.{your data type} will help you to disply the message.

Required filed validation

a. Put attribute as required in HTML control.
b..$error.required helps you to display the required field message.



 

11. What is $rootscope and how do we use it?

Ans:

$rootscope provides access to the top of the scope hierarchy, a scope provides a separation between View and its Model. Every application has a $rootScope provided by AngularJS and every other scope is its child scope.

 

12. Explain what is Dependency Injection in AngularJS?

Ans:

Dependency Injection is one of the best features of AngularJS. It is a software design pattern in which objects are passed as dependencies. It helps us to remove hard coded dependencies and makes dependencies configurable. Using Dependency Injection, we can make components maintainable, reusable and testable.

Dependency Injection is required for the following
Separating the process of creation and consumption of dependencies.
It allows us to create independent development of the dependencies.
We can change the dependencies when required.
It allows injecting mock objects as dependencies for testing.
AngularJS uses dependency with several types
Value
Factory
Service
Provider
Constant
A simple case of dependency injection in Angular js

AppModule.controller("AppController", function($scope, $window, $log,$http) 
{

});

13. Explain Convert Text To Uppercase Using AngularJS.

Ans:

AngularJS provides a feature for converting all the letters of text into uppercase letters. I will explain this feature by creating a sample application.

First of all you need to add an external Angular.js file to your application, in other words “angular.min.js”.For this you can go to the AngularJS official site. After downloading the external file you need to add this file to the Head section of your application.

14. Explain ng-repeat directive.

Ans:

The ng-repeat directive is the most used and very useful AngularJS Directive feature. It iterates over a collection of items and creates DOM elements. It constantly monitors the source of data to re-render a template in response to change.

Here, ng-repeat directive iterates over the empDetails collection and creates a

DOM element for each entry in the collection.

The ng-repeat directive creates a new scope for each element of a collection.

Variables created by ng-repeat

AngularJS ng-repeat directive creates so many special variables in a scope created for each and every individual entry. These variables are very important to find the position of an element within a collection.

Below are the some important variables created by ng-repeat
$index
$first
$middle
$last

15. What is controller in AngularJS?

Ans:

A controller is a set of JavaScript functions which is bound to a specified scope, the ng-controllerdirective. Angular will instantiate the new controller object, and injects the new scope as a dependency. It contains business logic for the view and avoids using controller to manipulate the DOM.

Controller in AngularJS

Controller in AngularJS

Controller Rules

  • We can use controller to set up the initial state of the scope object and add behavior to that object.
  • We do not use controller to manipulate DOM. It should contain only business logic and can use data binding and directives for the DOM manipulation.
  • We do not use controllers to format input but can use angular from controls instead of that.
  • We do not use filter output but can use angular filters instead of that.
  • We do not use controllers to share code or state across controllers but can use angular services instead of that.
  • We do not manage the life-cycle of other components.

Creating a Controller

  • Requires ng-controller directive.
  • Add controller code to a module.
  • Name your controller based on functionality.
  • Controllers are named using camel case (i.e. SimpleController).
  • Setup the initial state of the scope object.

ng-Controller directive

ng-Controller directive is an associated controller class to the view.

 

16. What are the filters in AngularJS?

Ans:

Filters are used to modify the data and can be clubbed in expression or directives using a pipe character. A filter formats the value of an expression for display to the user. They can be used in view templates, controllers, or services, and we can easily create our own filter. Filter is a module provided by AngularJS. There are nine components of filter which are provided by AngularJS. We can write custom as well.

  • currency
  • date
  • filter
  • json
  • limitTo
  • lowercase
  • number
  • orderBy
  • uppercase

Currency It will change all the digits to currency and “$” is the default currency.
{{ x | currency}}

Output:

Currency example:
$1.00
$1,000.00

Date

It will change all the digits into the date according to some rules, like the default date will be “44 years 2 months 10 days” earliar and 1000 will add 1 second into it.

{{ x | date:’medium’ }}

Output:

Change the 1 and 1000 into dates.
Date example:
Ramesh
Jan 1, 1970 5:30:00 AM
Jan 1, 1970 5:30:01 AM
Suresh

Filter

{{ filter_expression | filter : expression : comparator}}

limitTo

It will show the values depending on the limit of an array variable that has been set.

{{ names | limitTo:2 }}

Output
limitTo example:
[“Ramesh”,1]

Here the limit is 2, so you can only see 2 values.

lowercase

It will change all the letters into lowercase as in the following:

{{ x | lowercase }}

Output
lowercase exampe
ramesh
1
1000
suresh

Number

It will show all the digits with 3 decimal places by default as in the following:

{{ x | number:8}}

Output I am using 8 here.
Number example
1.00000000
1,000.00000000

OrderBy

{{ orderBy_expression | orderBy : expression : reverse}}

uppercase

It will change all the letters to uppercase.

{{ x | uppercase }}

Output
UPPERCASES EXAMPLE-
RAMESH
1
1000
SURESH

17. Explain Module And Controller In AngularJS.

Ans:

AngularJS module is nothing but a container of all angular components like controller, services, directive, filter, config etc

What is Module

Let me explain why module is required in AngularJS. In .NET console application there is a main method and what main method does is, it’s an entry point of application. It is the same as angular module and is an entry point. Using module we can decide how the AngularJS application should be bootstrapped.

We can create a simple module using the following code.

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

In the above code myModuleApp is the module name and if this module is dependent on other modules we can inject in “[]”.

What is Controller?

Controller is a JavaScript constructor function which controls the data. I am not going to cover what are the types of functions in this article but let me give some brief information about constructor function. In constructor function when we call that function that function creates a new object each time.

Let’s make a controller.

myApp.controller(‘myController’, function($scope)
{

});

 
Controller In AngularJS

Controller In AngularJS

18. What are the services in AngularJS?

Ans:

Services are one of the most important concepts in AngularJS. In general services are functions that are responsible for specific tasks in an application. AngularJS services are designed based on two principles.
Lazily instantiated

Angular only instantiates a service when an application component depends on it using dependency injection for making the Angular codes robust and less error prone.

Singletons

Each component is dependent on a service that gets a reference to the single instance generated by the service factory.

AngularJS provides many built in services, for example, $http, $route, $window, $location and so on. Each service is responsible for a specific task, for example, $http is used to make an Ajax call to get the server data. $route defines the routing information and so on. Builtin services are always prefixed with the $ symbol.
AngularJS internal services

AngularJS internally provides many services that we can use in our application. $http is one example. There are other useful services, such as $route, $window, $location and so on. Some of the commonly used services in any AngularJS applications are listed below.

  • $window Provide a reference to a DOM object.
  • $Location Provides reference to the browser location.
  • $timeout Provides a reference to window.settimeout function.
  • $Log Used for logging.
  • $sanitize Used to avoid script injections and display raw HTML in page.
  • $Rootscope Used for scope hierarchy manipulation.
  • $Route Used to display browser based path in browser URL.
  • $Filter Used for providing filter access.
  • $resource Used to work with Restful API.
  • $document Used to access the window. Document object.
  • $exceptionHandler Used for handling exceptions.
  • $q: Provides a promise object
Services in AngularJS

Services in AngularJS

19. Explain double click event in AngularJS?

Ans:

ng-dblclick allows you to specify custom behavior on a double-click event of the mouse on the web page. We can use it (ng-dblclick) as an attribute of the HTML element like,

<ANY_HTML_ELEMENT ng-dblclick="{expression}"> 
...
</ANY_HTML_ELEMENT>

Use the following procedure to create a sample of a double-click event using AngularJS.

First of all you need to add an external Angular.js file to your application, for this you can go to the AngularJS official site or download my source code and then fetch it or click on this link and download it: ANGULARJS. After downloading the external file you need to add this file to the Head section of your application as in the following,

Complete Code

<!doctype html> 
<html ng-app>
<head>
<script src="angular.min.js"></script>
</head>

<body>
Name:
<input ng-model="name" type="text" />
<button ng-dblclick="Msg='Hello '+name">
Double Click
</button>
</br>
<h3>
{{Msg}}</h3>
</body>
</html>

Output
Initially when Page loads

double click event in AngularJS

double click event in AngularJS

Before double-click

Before double click

Before double click

After double-click

After double click

After double click

20. Explain ng-include, Click, and Repeat directive in AngularJS.

Ans:

ng-include is an AngularJS directive, it is very helpful to include the various files in a main page using the ng-include attribute.

For example, you have one page layout that contains a header, body, footer and so on. In that scenario, you can create various HTML files for a header and footer then you can include those in the main HTML file. Because of this implementation the page looks cleaner and the code/design is also separated.

ng-include

ng-include

ng-click

This is also one of the directives; you can use this in one of the scenarios like when you click on a button. If you do any operation then this will be useful.

The form contains an input text box and Search button, whenever the user enters a value into a text box and clicks on the search button you need to display the user-entered value, if the user clicks on the search button without entering anything then we need to display a message.

The index.html file looks as in the following.

ng-click

ng-click

ng-repeat

This directive is like a foreach loop in C#. By using this directive you can display a collection of items in a view (HTML page).

You can display a list of employees using the ng-repeat directive in AngularJS.

<!DOCTYPE html> 
<html>
<head>
<!-- 1. Angular JS Script CDN reference added -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<!-- 2. Script JS Reference -->
<script src="Employee.js"></script>
</head>
<!-- 3. ng-app directive included -->
<body ng-app="DemoRepeatApp">
<h1>List of Emplooyees</h1>
<!-- 4. ng-controller directive included -->
<form ng-controller="DemoController">
<table>
<thead>
<tr>
<th>Name</th>
<th>Designation</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<!-- 5. ng-repeat directive included -->
<tr ng-repeat="emp in employees">
<td>{{emp.Name}}</td>
<td>{{emp.Designation}}</td>
<td>{{emp.Location}}</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

 

  



 

21. Explain ng-disabled Directive in AngularJS.

Ans:

ng- disabled directive is used to enable or disable HTML elements. Let us see this with the help of an example.
Write the following HTML mark up in the webpage.

<!doctype html> 
<html ng-app>

<head>
<title>My Angular App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>

<body>
<div ng-app="" ng-init="Switch=true">

<p>
<input type="checkbox" ng-model="Switch" />
</p>
<p>
<button ng-disabled="Switch">Submit</button>
</p>

</div>
</body>

</html>

In the above example we have a checkbox and a button. If the checkbox is selected the button is disabled, but if we uncheck the checkbox then the button is enabled.

So let us check the output of the program.

ng-disabled Directive in AngularJS

ng-disabled Directive in AngularJS

When we select the checkbox let us see what happens!!

22. Explain ng-app directive.

Ans:

ng-app directive is used to define AngularJS applications. We can use this to auto-bootstrap an AngularJS application. It designates the root element of AngularJS application and is generally kept near theortag. We can define any number of ng-app directives inside the HTML document but only one AngularJS application can be bootstrapped automatically (auto-bootstrapped); the other applications needs to be bootstrapped manually.

23. Why are we using AngularJS and what are the advantages of AngularJS?

Ans:

As we know AngularJS follows the MVW* pattern and it allows us to build well-structured, testable, and maintainable front end applications.
Note W* means “whatever,” in place of which we use C (controller) or VM (view model)
Why we are using AngularJS

  • As we know AngularJS is based on MVC pattern; it helps us to organize our web apps or web application properly.
  • It helps to make responsive and well organized web applications that are more expansive and readable.
  • It follows two way data binding. Two way data binding helps us so that any changes in model will be updated view and vice-versa without any manipulation on DOM or events.
  • AngularJS supports create your own directive that makes reusable components to be used according to your requirement. It is also abstract DOM manipulation logic.
  • It supports services and dependency injection which we can easily inject in our controller and provides some utility code as per our requirement.

Advantages of AngularJS

  • AngularJS has code reusability that allows us to write code & reuse it as required as Custom directive.
  • AngularJS supports powerful data binding; it is two way data binding with the help of HTML & scope.
  • AngularJS is easily customizable as per our requirement. Here we can create own custom components like directive and services.
  • AngularJS has good support over the internet and over time it has new changes available for developers. It also supports IE, Opera, Safari, and Chrome.
  • AngularJS has inbuilt form validation & template with all old plain html.
  • AngularJS has easily testable Unit testing, it doesn’t need to load all the app, just loading that specific module is enough to start unit testing.

24. What is Representational State Transfer(REST) in AngularJS.

Ans:

REST is a style of API that operates over HTTP requests. The requested URL identifies the data to be operated on, and the HTTP method identifies the operation that is to be performed. REST is a style of API rather than a formal specification, and there is a lot of debate and disagreement about what is and isn’t RESTful, a term used to indicate an API that follows the REST style. AngularJS is pretty flexible about how RESTful web services are consumed. You should use the services that I describe in this article when you are performing data operations on a RESTful API. You may initially prefer to use the $http service to make Ajax requests, especially if you are coming from a jQuery background. To that end, I describe the use of $http at the start of the article, before explaining its limitations when used with REST and the advantages of using the $resource service as an alternative. For this, we first need to create a RESTful web API.

A REST web service is said to be RESTful when it adheres to the following constrants:

  • It’s URL-based.
  • It uses an Internet media type such as JSON for data interchange.
  • It uses standard HTTP methods (GET, PUT, POST, DELETE).
  • HTTP methods have a particular purpose when used with REST services. The following is the standard way that HTTP methods should be used with REST services,

POST should be used to,

  • Create a new resource.
  • Retrieve a list of resources when a large amount of request data is required to be passed to the service.
  • PUT should be used to update a resource.
  • GET should be used to retrieve a resource or a list of resources.
  • DELETE should be used to delete a resource.

For doing this, we first create a model class with the below mention members

name

String

Yes

category

String

Yes

price

number

Yes

25. Explain ng-Switch Directive in AngularJS.

Ans:

This directive is used to swap DOM structure conditionally in our template based on a scope expression. ngSwitchWhen or ngSwitchDefault directives are used to show and hide the element within ngSwitch directive. We can show or hide the element inside this directive and are required to place a “when” attribute per element. The “when” attribute is used to inform the ngSwitch directive which element is to display based on expression, if the matching expression is found, the element is displayed, else it is hidden.

26. Why we use $http service or ajax request in AngualrJS?

Ans:

Ajax is the foundation of the modern web application, and you will use the services that I describe in this article every time that you need to communicate with a server without causing the browser to load new content and, in doing so, dump your AngularJS application. That said, if you are consuming data from a RESTful API, then you should use the $resource service. I will describe REST and $resource in the next article, but the short version is that $resource provides a higher-level API that is built on the services I describe in this article and makes it easier to perform common data operations.

Making Ajax Requests

The $http service is used to make and process Ajax requests, which are standard HTTP requests that are performed asynchronously.

The first—and most common—is to use one of the convenience methods that the service defines, which I have described in the below table and which allows you to make requests using the most commonly needed HTTP methods.

get(url, config)

Performs a GET request for the specified URL.

post(url, data, config)

Performs a POST request to the specified URL to submit the specified data.

delete(url, config)

Performs a DELETE request to the specified URL.

put(url, data, config)

Performs a PUT request with the specified data and URL.

patch(url, data, config)

Performs a PATCH request with the specified data and URL.

head(url, config)

Performs a HEAD request to the specified URL.

jsonp(url, config)

Performs a GET request to obtain a fragment of JavaScript code that is then executed. JSONP, which stands for JSON with Padding, is a way of working around the limitations that browsers apply to where JavaScript code can be loaded from.

The other way to make an Ajax request is to treat the $http service object as a function and pass in a configuration object.

Configuring Ajax Requests

The methods defined by the $http service all accept an optional argument of an object containing configuration settings. For most applications, the default configuration used for Ajax requests will be fine, but you can adjust the way the requests are made by defining properties on the configuration object corresponding to the below table.

data

Sets the data sent to the server. If you set this to an object, AngularJS will serialize it to the JSON format.

headers

Used to set request headers. Set headers to an object with properties whose names and values correspond to the headers and values you want to add to the request.

method

Sets the HTTP method used for the request.

params

Used to set the URL parameters. Set params to an object whose property names and values correspond to the parameters you want to include.

timeout

Specifies the number of milliseconds before the request expires. transformRequest Used to manipulate the request before it is sent to the server.

transformResponse

Used to manipulate the response when it arrives from the server

url

Sets the URL for the request.

withCredentials

When set to true, the withCredentials option on the underlying browser request object is enabled, which includes authentication cookies in the request.

The most interesting configuration feature is the ability to transform the request and response through the aptly named transformRequest and transformResponse properties. AngularJS defines two built-in transformations; outgoing data is serialized into JSON, and incoming JSON data is parsed into JavaScript objects.

 

AngularJS file code

testApp.controller("ajaxController", function($scope, $http) 
{

$scope.loadData = function()
{
$http.get(“data.json”).success(function(data)
{
$scope.products = data;
});
}

$scope.loadXMLData = function()
{
var config =
{
transformResponse: function(data, headers)
{
if ((headers(“content-type”) == “application/xml” || headers(“content-type”) == “text/xml”) && angular.isString(data)) {
products = [];
var productElems = angular.element(data.trim()).find(“product”);
for (var i = 0; i < productElems.length; i++)
{
var product = productElems.eq(i);
products.push
({
Category: product.attr(“Category”),
Book: product.attr(“Book”),
Publishers: product.attr(“Publishers”),
price: product.attr(“price”)
});
}
return products;
} else
{
return data;
}
}
}
$http.get(“data.xml”, config).success(function(data)
{
$scope.products = data;
});
}
});

27. Why to use AngularJS Global Object services?

Ans:

The main reason that AngularJS includes these services is to make testing easier, but an important facet of unit testing is the need to isolate a small piece of code and test its behavior without testing the components it depends on—in essence, creating a focused test. The DOM API exposes functionality through global objects such as document and window.

These objects make it hard to isolate code for unit testing without also testing the way that the browser implements its global objects. Using services such as $document allows AngularJS code to be written without directly using the DOM API global objects and allows the use of AngularJS testing services to configure specific test scenarios.

The followings are the services that expose DOM API features.

$anchorScroll

Scrolls the browser window to a specified anchor

$document

Provides a jqLite object that contains the DOM window.document object

$interval

Provides an enhanced wrapper around the window.setInterval function

$location

Provides access to the URL

$log

Provides a wrapper around the console object

$timeout

Provides an enhanced wrapper around the window.setITimeout function

$window

Provides a reference to the DOM window object

28. When and Why to use and create Services?

Ans:

Services are used to encapsulate functionality that we need to reuse in an application but don’t fit clearly into Model-View-Controller pattern as we discussed in the article. Services are mainly used for the purpose of cross cutting concerns. The AngularJS Module defines three methods for defining services : factory, service and provider. The result of using these methods is the same – a service object that provides functionality that can be used throughout the AngularJS application – but the way that the service object is created and managed by each method is slightly different. Below I mentioned the built in services of AngularJS.

$anchorScroll

Scrolls the browser window to a specified anchor

$animate

Animates the content transitions.

$compile

Processes an HTML fragment to create a function that can be used to generate content.

$controller

A wrapper around the $injector service that instantiates controllers

$document

Provides a jqLite objects that contains the DOM window.documentobject.

$exceptionHandler

Handles exceptions that arise in the application.

$filter

Provides access to filters

$http

Creates and manages Ajax requests

$injector

Creates instances of AngularJS components

$interpolate

Processes a string that contains binding expressions to create a function that can be used to

generate content.

$interval

Provides an enhanced wrapper around the window.setInterval function.

$location

Provides a wrapper around the browser location object.

$log

Provides a wrapper around the global console object.

$parse

Processes an expression to create a function that can be used togenerate content.

$provide

Implements many of the methods that are exposed by Module.

$q

Provides deferred objects/promises.

$resource

Provides support for working with RESTful APIs.

$rootElement

Provides access to the root element in the DOM.

$rootScope

Provides access to the top of the scope hierarchy

$route

Provides support for changing view content based on the browser’sURL path.

$routeParams

Provides information about URL routes.

$sanitize

Replaces dangerous HTML characters with their display-safecounterparts.

$swipe

Recognizes swipe gestures.

$timeout

Provides an enhanced wrapper around the window.setITimeout function.

$window

Provides a reference to the DOM window object.

I will discuss about this built in service of AngularJS in a later article. The main focus of this article is what are the different ways to create custom services as per our requirement in AngularJS.

Using Factory method

The simplest method of defining a service is to use the Module.factory method, passing an argument, the name of the service and a factory function that returns the service objects. For doing this, we create three files as follows,

ServiceApp.Js

var serviceApp = angular.module('ServiceApp', []);

serviceApp.factory(“logService”, function()
{
var messageCount = 0;
return
{
log: function(msg)
{
console.log(“(LOG + ” + messageCount++ + “) ” + msg);
}
};
});

In the above file, I first create an angular module named serviceApp for defining the factory service which creates log message on execution.

App.js

var testApp = angular.module('TestApp', ['ServiceApp']); 

Now, I define another angualr module named testApp in which I inject the ServiceApp module. This testApp module will be used from html page for controller.

Factory.html

<!DOCTYPE html> 
<html ng-app="TestApp">
<head>
<title>AngularJS Factory</title>
<script src="angular.js"></script>
<link href="../../RefStyle/bootstrap.min.css" rel="stylesheet" />
<script src="serviceApp.js"></script>
<script src="app.js"></script>
<script src="Factory.js"></script>
</head>
<body ng-controller="FactoryController">
<div class="well">
<div class="btn-group" tri-button counter="data.totalClicks" source="data.device">
<button class="btn btn-default" ng-repeat="item in data.device">
{{item}}
</button>
</div>
<h5>Total Clicks: {{data.totalClicks}}</h5>
</div>
</body>
</html>


Factory.js

testApp.controller('FactoryController', function($scope, logService) 
{
$scope.data =
{
device: ["Mobile", "Laptops", "IPad"],
totalClicks: 0
};

$scope.$watch(‘data.totalClicks’, function(newVal)
{
logService.log(“Total click count: ” + newVal);
});

});

testApp.directive(“triButton”, function(logService)

{
return
{
scope:
{
counter: “=counter”
},
link: function(scope, element, attrs)
{
element.on(“click”, function(event)
{
logService.log(“Button click: ” + event.target.innerText);
scope.$apply(function()\
{
scope.counter++;
});
});
}
}
});

The output is as follows,

use and create Services

use and create Services

29. Explain Provider Method in AngularJS.

Ans:

The Module.provider method allows you to take more control over the way that a service object is created or configured. The arguments to the provider method are the name of the service that is being defined and a factory function. The factory function is required to return a provider object that defines a method called $get, which in turn is required to return the service object. When the service is required, AngularJS calls the factory method to get the provider object and then calls the $get method to get the service object. Using the provider method doesn’t change the way that services are consumed, which means that I don’t need to make any changes to the controller or directive in the example.

The advantage of using the provider method is that you can add functionality to the provider method that can be used to configure the service object.

To demonstrate this process, I again change the serviceapp.js file as below,

var serviceApp = angular.module('ServiceApp', []);

serviceApp.provider(“logService”, function()
{
var counter = true;
var debug = true;
return
{
messageCounterEnabled: function(setting)
{
if (angular.isDefined(setting))
{
counter = setting;
return this;
} else
{
return counter;
}
},
debugEnabled: function(setting)
{
if (angular.isDefined(setting))
{
debug = setting;
return this;
} else
{
return debug;
}
},
$get: function()
{
return
{
messageCount: 0,
log: function(msg)
{
if (debug)
{
console.log(“(LOG” + (counter ? ” + ” + this.messageCount++ + “) ” : “) “) + msg);
}
}
};
}
}
});

30. What is event handling in AngularJS?

Ans:

When we want to create advanced AngularJS applications such as User Interaction Forms, then we need to handle DOM events like mouse clicks, moves, keyboard presses, change events and so on. AngularJS has a simple model for how to add event listeners. We can attach an event listener to an HTML element using one of the following AngularJS event listener directives.

  • ng-click
  • ng-dbl-click
  • ng-mousedown
  • ng-mouseup
  • ng-mouseenter
  • ng-mouseleave
  • ng-mousemove
  • ng-mouseover
  • ng-keydown
  • ng-keyup
  • ng-keypress
  • ng-change

 

31. What are the top reasons why developers choose AngularJS?

Ans:

AngularJS, an Open Source web application framework by Google, is widely used in building highly robust and scalable Single Page Applications (SPA). Single Page Applications are websites or web applications that encompass a single web page, rendering a seamless and immersive user experience. The framework is written in JavaScript, and allows using HTML as template language. It helps build rich and intuitive web applications, and also provides web developers the option to build client-side applications.

High Performance

AngularJS is a popular choice among web developers because of ease of use and maintenance, intuitive features, robustness, and the efficiency to build new features. It is obvious that when a problem arises, developers are not ready to spend hours debugging it. At the same time, they should be able to make minor changes with much ease. AngularJS gives you the ease of maintenance.

Effective Handling of Dependencies

AngularJS does dependency injection extremely well. For Single Page Applications, Angular makes it extremely easy to organize things like dynamic loading and dependencies, and use them as required without worrying about “Did I spin up an instance?” or “What namespace does it live in?” Simply mention what you need, and Angular will get it for you and also manage the entire life-cycle of the objects.

For testing, the framework allows you to segregate the app into logical modules that may have dependencies on each other, but are separately initialized. This helps to take a tactical approach towards testing as it provides only the modules that you need. Now, since the dependencies are injected, you can have an existing service like Angular $HTTP and swap it easily with $httpBackend mock for effective testing.

DOM has Markup in AngularJS

In most client-side JavaScript frameworks, the temples operate in something like this way,
Template with markup -> framework template engine -> HTML -> DOM

However, in AngularJS, the markup is directly put into the HTML document and flow looks something like this,

HTML with Angular markup -> DOM -> Angular Template Engine

The framework evaluates the markup only when HTML has been loaded into DOM.
This has three major benefits – simplicity, integration with existing apps, and extensibility. You can work with AngularJS in basic HTML documents from a local file system. Additionally, it allows you to build custom attributes and elements that can extend the basic HTML vocabulary.

32. Explain $routeProvider in AngularJS?

Ans:

The $routeProvider is used to set the configuration of urls and map them with the corresponding html page or ng-template and also attach a controller. Routing in AngularJS is taken care of by a service provide that is called $routeProvider. Routes for templates and urls in Angular are declared via the$routeProvider, that is the provider of the $route service. This service makes it easy to wire together controllers, view templates, and the current URL location in the browser.

We can use config() method of “myApp” module to configure $routeProvider. The when method of$routeProvideris used to bind the url with a template. This method takes a url(i.e. “/viewDelhi”) that will map with a template (i.e. delhi.htm) using the templateUrl parameter. The when method also binds a controller for templates using the controller parameter (i.e. controller: ‘AddDelhi’), otherwise the method is used to set the default view.

Example

mainApp.config(['$routeProvider', function($routeProvider) 
{
$routeProvider.
when('/viewDelhi',
{
templateUrl: 'delhi',
controller: 'AddDelhi'
}).
when('/viewMumbai',
{
templateUrl: 'mumbai',
controller: 'AddMumbai'
}).
when('/viewJaipur',
{
templateUrl: 'jaipur',
controller: 'AddJaipur'
}).
otherwise
({
redirectTo: '/viewDelhi'
});
}]);

33. What are the attributes can be used during creation of a new AngularJS Directives?

Ans:

The following attributes can be used during creation of a new AngularJS Directives,

Restrict

The restrict attribute is how AngularJS triggers the directive inside a template. The default value of the restrict option is “A”. The value of “A” causes the directives to be triggered on the attribute name. Other than “A”, restrict option has “E” (only match element name), “C” (only match class name) and “M” (only match the comment name) or any combination among four options.

TemplateUrl

The templateUrl attribute tells the AngularJS HTML compiler to replace custom directive inside a template with HTML content located inside a separate file. The link-Menu (say, our custom directive name) attribute will be replaced with the content of our original menu template file.

Template

Specify an inline template as a string. Not used if you’re specifying your template as a URL.

Replace

If true, replace the current element. If false or unspecified, append this directive to the current element.

Transclude

Lets you move the original children of a directive to a location inside the new template.

Scope

Create a new scope for this directive rather than inheriting the parent scope.

Controller

Create a controller which publishes an API for communicating across directives.

Require

Require that another directive be present for this directive to function correctly.

Link

Programmatically modify resulting DOM element instances, add event listeners, and set up data binding.

Compile

Programmatically modify the DOM template for features across copies of a directive, as when used in other directives. Your compile function can also return link functions to modify the resulting element instances.

34. What are the different types of Directives in AngularJS?

Ans:

Directives are one of the most important components of AngularJS application. They are extended HTML attributes. In other words, directives are something that introduces new syntax. They are markers on the DOM element which provides some special behavior to DOM elements and tell AngularJS’s HTML compiler to attach.

Their are many built in directives such as ng-model, ng-repeat, ng-show, ng-bind etc. All these directives provide special behavior to DOM elements. For example, ng-show directive conditionally shows an element, ng-click directive adds click events to the element; ng-app directive initializes an AngularJS application, etc.

Types of Directives

Type of directive determines how they are used. We can implement directives in the following ways,
Attribute directives Directive is active when matching attribute is found.

Example

<input type="text" numeric /> 

Element directives Directive is active when matching element is found.

Example

<numeric-Textbox id = "txtAge" /> 

Component directives Directive is active when matching component is found.

Example

<!-- directive: numeric-Textbox exp --> 

CSS class directives Directive is active when matching CSS style is found.

Example

<input type="text" class=" numeric "/>  

35. What are compile & link options in Custom Directives?

Ans:

Understanding the compile vs. link option is one of the more advanced topics across AngularJS, and it gives us a feel for how Angular actually works. Out of both the functions the link function is used very often. Basically both are mutually exclusive; i.e,. if both the options are set then compile will overwrite the link functions defined. 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.

Compile

It traverses the DOM and collects all of the directives and deals with transforming the template DOM. The result is a linking function.

Link

The link function deals with linking scope to the DOM.

Using Code for Compile

While defining a custom directive we have the option to define a link against which either we can define a function or we have the option to assign an object which will have pre and post function.

Compile and link options in Custom Directives

Compile and link options in Custom Directives

If compile is defined as defined below then it will override the link function as shown in below example.

Using Code for Pre & Post Link

While defining a custom directive we have the option called “link” against which either we can define a single function or we have the option to assign an object in which we can define further two functions i.e. Pre-link and Post- link functions.

If only a single function is defined against link option that will be same as Post link function.

Both Pre and Post link function have the same syntax as defined below but the only difference is the order in which they get executed.

Link example,

Code for Pre and Post Link

Code for Pre and Post Link

In the above example we are defining a function against link option which will get executed before linking scope and the template.

36. Explain what is injector in AngularJS?

Ans:

The $injector service is responsible for determining the dependencies that a function declares and resolving those dependencies. The below table lists the methods supported by the $injector service.

annotate(fn)

Gets the arguments for the specified function, including those that do not correspond to services

get(name)

Gets the service object for the specified service name

has(name)

Returns true if a service exists for the specified name

invoke(fn, self, locals)

Invoked the specified function, using the specified value for this and the specified non-service argument values.

The $injector service is right at the core of the AngularJS library, and there is rarely a need to work directly with it, but it can be useful for understanding and customizing how AngularJS works. However, these are the kind of customizations that should be considered carefully and tested thoroughly.

Getting the $injector Service from the Root Element

The $rootElement service provides access to the HTML element to which the ng-app directive is applied and which is the root of the AngularJS application. The $rootElement service is presented as a jqLite object, which means you can use jqLite to locate elements or modify the DOM using the jqLite methods I described in Chapter 15. Of interest in this chapter, the $rootElement service object has an additional method called injector, which returns the $injector service object. You can see how I replaced the dependency on the $injector service with the $rootElement service.

37. Mention what are the characteristics of “Scope”?

Ans:

$scope is a glue between the View and the Controller. It connects a Controller with the View,

$scope serves as the glue between the Controller and the View.

The $scope is the connection between the HTML and the View.

The View and the model both have access to the $scope.

In the context of MVC, $scope can be seen as the ViewModel.

$scope provides the execution context for the DOM and the expression.

$scope provides an execution context in which the DOM element is bound.

$scope is the source of the truth.

$scope is modified when the View changes and the View is modified when $the scope changes its value.

The $scope object is a plain JavaScript object. We can add and remove a property as required.

$scope holds data and functions from the Controller that should be displayed and executed in the View.

The $rootScope is the eventual parent of all the $scope.

$rootScope is the top-most scope in a DOM element with the ng-app directive.

In angular all the $scope are created with prototypal inheritance.

$scope has access to their parent scope.

$scope contains data and the functionality to be used to render the View.

For each Controller created a new $scope is created.

It is ideal to contain the application logic in the Controller and the data in the $scope of the Controller.

When $the scope object is not needed in the View, the scope will be cleaned up and destroyed.

Directives do not have their own scope but with some exceptions ng-controller and ng-repeat do.

When angular starts running all the $scope are attached to the View.

$scope passes data and behavior to the View.

38. Give the differences between AngularJS and Backbone and Knockout?

Ans:

Comparison with Backbone.js and Knockout.js,

File Size

~142 KB total (compressed and minified)

~ 7.3 KB total (gzip / minified)

~21 KB total (gzip / minified)

Version & Licence

V1.4.2 & MIT (Open-source)

V1.2.1 & MIT (Open-source)

V3.3.0 & MIT (Open-source)

Dependencies

No Dependencies

Dependends on underscore.js and jQuery

No Dependencies

Data Binding

It supports full data binding and provides options for creating custom data bindings

Does not support data binding by default but does using plugins for data bindings

It fully supports data binding and can bind many attributes.

It provides options for creating custom data bindings

Routing

It supports routing feature and it’s very simple

It supports routing features and it’s very simple

Does not support routing by defualt but it is available with some thrid-party libraries

Views

Uses HTML as the templating language

Does not have templates by default but we can add them easily by a thrid-party template like underscore.js and handlebars

It uses HTML as the templating language

Testing

Can support Test Driven Development (TDD)

Does not support testing by defualt but we can use some thrid-party tester like Jasmine and Sinon.JS

Does not support testing by defualt but we can use some thrid-party tester like Jasmine and Sinon.JS

Data

Does not support jQuery but we can use Angular’s $http

Can support jQuery’s $.ajax and is very easy to understand

It can support jQuery’s $.ajax and knockout mapping

Design Pattern

Can support the MVC and MVVM design patterns

It can support MVP design pattern

It can support the MVVM design pattern

Browser

Can support IE 9, IE 10 and IE 11

It dependends on jQuery supporting browsers like IE 6+, Chrome, Firefox, Safari 5.1+ and Opera

It can support all major browsers like IE 6+, Firefox 3.5+, Chrome, Opera and Safari

Third-party Integration

Does not support third-party integration

Does not support third-party integration

It supports third-party integration

Documentation

It has available documentation and community

To my knowledge there is no documentation

It has available documentation and community

39. What is the difference between AngularJS and jQuery?

Ans:

jQuery and AngularJS have some common features like Unit test runner, animation support, AJAX/JSONP but they also have some differences.
AngularJS came with RESTful API whereas we don’t have that in jQuery.
AngularJS supports the MVC pattern whereas jQuery doesn’t.
AngularJS has the feature called Two Way Data Binding whereas we don’t have that in jQuery.
Deep Linking Routing is supported by AngularJS whereas jQuery doesn’t.
The AngularJS file size is quite heavier than that of the jQuery file size.
We can prefer AngularJS only if we are developing a heavy web application.

40. What are the custom directives in AngularJS?

Ans:

In AngularJS we can create the custom directive for the following types of elements.

Element directives Directive activates when a matching element is encountered. Restrict mode is defined by “E”.

Attribute Directive activates when a matching attribute is encountered. Restrict mode is defined by “A”.

CSS Directive activates when a matching css style is encountered. Restrict mode is defined by “C”.

Comment Directive activates when a matching comment is encountered. Restrict mode is defined by “M”.



 

41. What is AngularJS BootStrap Process?

Ans:

Bootstrapping an angular application is as simple as making coffee for yourself.

There are two ways to bootStrap Angular Application.
Automatic BootStrap (Coffee by Machine)
Manual BootStrap (Handmade coffee, you can face some trouble)
Automatic BootStrap

When DOM content is loaded, Angular looks for the ngApp directive which designates application root.
If it finds ngApp directive

a. It loads the module associated with this directive.

<html ng-app='myApp'> 
<head>
<script src='angular.js'>
</script>
<script>
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
$scope.message = 'Dear';
});
</script>
</head>
<body>
<div ng-controller="myController">
<p> Hi {{ message}} </p>
</div>

From the above script, It will load “myApp”.

Now let’s move to the Manual process of bootstraping an Angular application.

Manual Bootstrap:

There is a big difference in Automatic and manual Bootstrap.
You do not need to attach ng-app directive with the html element.
You call function angular.bootstrap(document,[‘myApp’]).

<!doctype html> 
<html>
<body>
<div ng-controller="myController"> Best movie: {{MovieName}}! </div>
<script src='angular.js'>
</script>
<script>
angular.module('myApp', []).controller('MyController', ['$scope', function($scope) {
$scope.MovieName = 'The IRON MAN';
}]);
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
</script>
</body>
</html>

Angular.bootstrap can not create a module for you until you make a custom module to give it as a parameter inside.

Before bootstrapping the process you need to add controllers, directives and services etc.

Manual bootstrap comes into picture when you need more control over the initialization process, like if you want to perform an operation before Angular compiles a page.

NOTE You should not use ng-app directive in case of manual bootstrapping of an angular application.

42. What is Constants in AngularJS?

Ans:

Constant are like services in AngularJS in which we can define our global data. It is declared using “constant” keyword.

As we define our app-keys in Web.Config file for ASP.NET application, which further we can use anywhere in the application, likewise we can declare constant data in AngularJS globally that can be used throughout the application.

We can inject Constant everywhere in controller or service like any other dependency (e.g.$http).AngularJS uses Singleton structure for creating Constant dependency in our Angular application.

So, using the Constant you can create your Config.js file and it can be injected anywhere in your application.

Now, let’s start to define constant and will use it in controller.

First of all create angular module

var app = angular.module('ConstantApp', []) 

Then, create Config.js file and define Constant in it,

app.constant('config', 
{
appName: 'Constants',
appVersion: 2.0
});

Now, use the above to declare Constant in our controller,

app.controller('mainController', function ($scope,config) {

$scope.ApplicationName = config.appName;
}

At last now consume this scope in our HTML view,

 

Conclusion

You can use constants for a lot of things. This blog is just a basic demo explanation about constant.

43. Which Angular Directive Would You Use To Hide An Element From The DOM Without Modifying Its Style?

Ans:

It is the conditional ngIf Directive which we can apply to an element. Whenever the condition becomes false, the ngIf Directive removes it from the DOM.

44. What is One-Way Data Binding in AngularJS?

Ans:

One-Way Data Binding simply means that HTML elements reflect the change. When the model values change the HTML elements don’t change the values in the model.

In other words, when the model changes, this change is reflected in the view but the view doesn’t change the model. In other words the developer must write extra code for automatic synchronization of data between the model and the view components. One-Way binding may also be called one-direction binding.

45. What is One-Way Data Binding in AngularJS?

Ans:

One of the core features of AngularJS which makes it popular is two way data binding. In two way data binding, any changes to the model are immediately reflected in the View and any changes in the View updates the model.

46. What Is The Difference Between One-Way Binding And Two-Way Binding?

Ans:

The main difference between one-way binding and two-way binding is as follows.

In one-way binding, the scope variable in the HTML gets initialized with the first value its model specifies.
In two-way binding, the scope variable will change its value whenever the model gets a different value.

47. What are animating elements in AngularJS?

Ans:

The $animate service allows you to provide transition effects when elements are added, removed, or moved in the DOM. The $animate service doesn’t define any animations itself but relies on the CSS3 animation and transition features. Animations can be a useful means of drawing the user’s attention to an important change in the layout of an application, making the transition from one state to another less jarring. Many developers treat animations as an outlet for their frustrated artistic ambition and ladle on as many as possible. The results can be annoying, especially for the user who has to endure endless special effects every time they perform a task. For a line-of-business application, where the user could be repeating the same set of actions all day, the effect is demoralizing beyond description. Animations should be subtle, brief, and quick. The goal is to draw the user’s attention to the fact that something has changed. Use animations consistently, cautiously, and—above all—sparingly.

Defining and Applying an Animation

You don’t work directly with the $animate service to apply animations. Instead, you define animations or transitions with CSS, following a special naming convention, and then apply those names as classes to elements, which also have AngularJS directives.

The built-in directives that support animation and the names associated with them: The name enter is used when content is shown to the user. The name leave is used when content is hidden from the user. The name move is used when content is moved within the DOM. The names add and remove are used when content is added and removed from the DOM.

ng-repeat

enter, leave, move

ng-view

enter, leave

ng-include

enter, leave

ng-switch

enter, leave

ng-if

enter, leave

ng-class

add, remove

ng-show

add, remove

ng-hide

add, remove

48. What is ngClass directive in AngularJS?

Ans:

ngClass directive This directive lets us do things like,
Add/Remove classes based on Angular variables.
Add/Remove classes based on evaluated expressions.
Bind single or multiple classes based on dynamic data.
Some Points about ng-class
The ng-class directive dynamically binds one or more CSS classes to an HTML element.
The value of the ng-class directive can be a string, an object, or an array.
If it is a string, it should contain one or more, space-separated class names.
As an object, it should contain key-value pairs, where the key is a Boolean value, and the value is the class name of the class you want to add. The class will only be added if the key is set to true.
Examples
Ex 1

<div ng-class="{class1 : expression1, class2 : expression2}"> 
Hello World!
</div>

Here class1 will apply if the expression1 is true and class2 will apply if the expression2 is true.

Ex 2

< div ng-class="{'class1 class2' : expression1}"> 
Hello World!

< /div>

Here class1 and class2 will apply if the expression1 is true.

We can reduce the above code into,

< div ng-class="{'class1 class2' : expression1}"> 
Hello World!

< /div>

49. Why is scopeless controller used in AngularJS?

Ans:

Sometimes controller become complex by using $scope for providing data and behavior to view, in that situation we can use scopeless controller.

But if you have designed your AngularJS application perfectly, there is no need to go for scopeless controllers.

Creating scope-less controller
angular module(app.js):

angular.module('myApp', []);
Controller (homeController.js)
var app = angular.module("myApp");

app.controller(“myController”, function()
{

this.title = ‘scopeless Controller Test’;
this.name = ‘Anupam’;
this.sayHello = function()
{
alert(‘Hello ‘ + this.name);
}

});

As you can see I have used JavaScript for this keyword to add data and behavior in my controller.

I would love to explain this here but I am still exploring what thi is in JavaScript.

Here is how we can get data from controller to view.

Binding Data to View using scope-less controller

View (index.html)

<!DOCTYPE html> 
<html ng-app="myApp" ng-controller="myController as ctrl">

<head>
<script src="Scripts/angular.min.js"></script>
<script src="app/app.js"></script>
<script src="app/homeController.js"></script>
<link href="Css/bootstrap.min.css" rel="stylesheet" />
<title>{{ctrl.title}}</title>
</head>

<body>
<nav role="navigation" class=" navbar navbar-default">
<div class="navbar-header">
<a href="#" class="navbar-brand">
{{ctrl.title}}
</a>
</div>

</nav>
<div class="container body-content">
<div class="col md-6">
<div class="row">
<div class="well-lg">
Hi {{ctrl.name}}
</div>
</div>
<div class="row">
<div class="well-lg">
<input type="button" ng-click="ctrl.sayHello()" value="Say Hello" class="btn" />
</div>
</div>
</div>
</div>
</body>

</html>

Here I have used a variable ctrl (myController as ctrl) which is an instance of myController.

50. What is AngularJS?

Ans:

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




 

51. Explain what are the key features of AngularJS ?

Ans:

The key features of AngularJS are

  • Scope
  • Controller
  • Model
  • View
  • Services
  • Data Binding
  • Directives
  • Filters
  • Testable

52. Explain what is scope in AngularJS ?

Ans:

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.

53. Explain what is services in AngularJS ?

Ans:

In AngularJS 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.

54. Explain what is Angular Expression? Explain what is key difference between angular expressions and JavaScript expressions?

Ans:

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

55. With options on page load how you can initialize a select box ?

Ans:

You can initialize a select box with options on page load by using ng-init directive

On = “! ! accounts” ng-init = “ loadData ( ) ”>

56. Explain what are directives ? Mention some of the most commonly used directives in AngularJS application ?

Ans:

A directive is something that introduces new syntax, they are like markers on DOM element which attaches a special behavior to it. In any AngularJS application, directives are the most important components.

Some of the commonly used directives are ng-model, ng-App, ng-bind, ng-repeat , ng-show etc.

57. Mention what are the advantages of using AngularJS ?

Ans:

AngularJS has several advantages in web development.

  • AngularJS supports MVC pattern
  • Can do two ways data binding using AngularJS
  • It has per-defined form validations
  • It supports both client server communication
  • It supports animations

58. Explain what Angular JS routes does ?

Ans:

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 AngularJS 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 AngularJS module.
Injecting a value into an AngularJS controller function is done by adding a parameter with the same name as the value

59. Explain what is data binding in AngularJS ?

Ans:

Automatic synchronization of data between the model and view components is referred as data binding in AngularJS. There are two ways for data binding

  • Data mining in classical template systems
  • Data binding in angular templates

60. What makes AngularJS better ?

Ans:

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: AngularJS 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 AngularJS you can bootstrap your app easily using services, which auto-injected into your application in Guice like dependency injection style


 

61. Explain what is string interpolation in Angular.js ?

Ans:

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.

62. Mention the steps for the compilation process of HTML happens?

Ans:

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

63. Explain what is directive and Mention what are the different types of Directive?

Ans:

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

64. Explain what is linking function and type of linking function?

Ans:

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.
Pre-linking function: Pre-linking 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 post-linking function

65. Explain what is injector?

Ans:

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.

66. Explain what is the difference between link and compile in Angular.js?

Ans:

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.

67. Explain what is factory method in AngularJS?

Ans:

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.

68. Mention what are the styling form that ngModel adds to CSS classes ?

Ans:

ngModel adds these CSS classes to allow styling of form as well as control

  • ng- valid
  • ng- invalid
  • ng-pristine
  • ng-dirty

69. Mention what are the characteristics of “Scope”?

Ans:

  • 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

70. Explain what is DI (Dependency Injection ) and how an object or function can get a hold of its dependencies ?

Ans:

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


 

71. Mention what are the advantages of using Angular.js framework ?

Ans:

Advantages of using Angular.js as framework are

  • Supports two way data-binding
  • 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

72. Explain the concept of scope hierarchy? How many scope can an application have?

Ans:

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.

73. Explain what is the difference between AngularJS and backbone.js?

Ans:

AngularJS 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.

74. Who created Angular JS ?

Ans:

Intially it was developed by Misko Hevery and Adam Abrons. Currently it is being developed by Google.

75. What Is AngularJS?

Ans:

It has been developed by one of the biggest technology giants Google. It is a JavaScript framework that helps you to create dynamic Web applications.
It supports to use HTML as the template language and enables the developer to create extended HTML tags that help to represent the application’s components more clearly. These tags make the code efficient by reducing the lines of code that a developer may need to write when using JavaScript.
It is open-source and licensed under the Apache License version 2.0.
It helps to develop a maintainable architecture that is easy to test at the client-end.

76. What Are The Main Features Of AngularJS?

Ans:

Here is the list of AngularJS features that makes it the hottest tech for web dev.

Data-binding – Handles synchronization of data across model, controllers, and view.
Scope – Object representing the model, acts as a glue layer between controller and view.
Controllers – JS functions bound to the scope object.
Services – Substitutable objects that are wired together using dependency injection. e.g. $location service.
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.
Templates – HTML code including AngularJS specific elements and attributes.
Routing – It’s an approach to switch views.
MVC pattern – A design pattern made up of three parts.
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.

77. Explain The Reasons That Compel A Web Developer To Choose AngularJS For His Web Development Project?

Ans:

Following are some of the key reasons to choose AngularJS as you web development framework:

It uses MVC design pattern which allows segregating an application into different components (called Model, View, and Controller) thus making it easy to maintain.
It allows the HTML to extend by adding directives to the HTML markup. This feature helps in defining dynamic templates which can include new attributes, tags, and expressions.
It allows the creation of user-defined directives and reusable components. These directives help the developer to concentrate on creating logic, thus enabling them to work efficiently.
It supports two-way data binding, i.e., enables automatic synchronization of data between model and view components. Thus, any update in the model gets reflected in the view automatically. And there is no need to add any Javascript code or event listeners to reflect the data changes.
It encapsulates the behavior of your application in controllers which gets instantiated with the help of dependency injection.
It supports built-in services to perform routine tasks for web applications. For example, it provides $http service to communicate with REST service.
It makes the development and testing of the application’s JavaScript code easy.
Also, AngularJS has a mature community to help the developers. It has broad support over the internet.

78. List Down The Popular AngularJS IDE Plugins/Extensions For Web Development?

Ans:

Here is a list of IDE Plugins and Extensions which can enhance the way you code with AngularJS:

  • Sublime Text
  • WebStorm
  • Eclipse
  • Netbeans
  • Visual Studio 2012/2013 Express or higher
  • TextMate
  • Brackets
  • ATOM

79. Explain The Steps Involved In The Boot Process For AngularJS?

Ans:

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.

80. What Browsers Do AngularJS Support?

Ans:

AngularJS works fine with the latest versions of Safari, Chrome, Firefox, Opera 15+, and IE9+ (Internet Explorer).
It also supports various mobile browsers like Android, Chrome Mobile, iOS Safari, and Opera Mobile.

Note: Versions 1.3 and later of AngularJS dropped support for Internet Explorer 8.




 

81. What Are The Security Features Provided By AngularJS?

Ans:

AngularJS provides built-in protection from the following security flaws.

It prevents cross-site scripting attacks: Cross-site scripting is a technique where anyone can send a request from client side and can get the confidential information easily.
It prevents HTML injection attacks.
It prevents XSRF protection for server-side communication: “Auth token” mechanism can handle it. When the user logins for the first time a user id and password is sent to the server, and it will, in turn, return an auth token. Now, this token does the authentication in the future transactions.

82. What Are The Web Application Security Risks That A Web Developer Should Avoid While Doing Development Using AngularJS?

Ans:

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)
  • Insecure direct object references.
  • Security Misconfiguration.
  • Sensitive Data Exposure.
  • Missing Function Level Access Control.
  • Cross-Site Request Forgery (CSRF).
  • Using components that possess vulnerabilities.
  • In-validated redirects and forwards.

83. Explain What Directives Are? Mention Some Of The Most Commonly Used Directives In AngularJS Application?

Ans:

AngularJS extends the behavior of HTML and DOM elements with new attributes called Directives. It directs the AngularJS’s HTML compiler ($compile) to attach a unique action to that DOM element. This AngularJS component starts with the prefix “ng.”

Following is the list of AngularJS built-in directives.

ng-bind – The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression.
If there is any change in the value of the given variable or expression, then the content of the specified HTML element will also be updated accordingly. It supports one-way binding only.
ng-model – This directive is used to bind the value of HTML controls (input, select, text area) to application data. It is responsible for linking the view into the model. Directives such as ‘input’, ‘text area’, and ‘select’ require it. It supports two-way data binding.
ng-class – This directive dynamically binds one or more CSS classes to an HTML element. The value of the ng-class directive can be a string, an object, or an array.
ng-app – Just like the “Main()” function of Java language, this directive marks the beginning of the application to AngularJS’s HTML compiler ($compile). If we do not use this directive first, an error gets generated.
ng-init – This is used to initialize the application data so that we can use it in the block where it is declared. If an application requires local data like a single value or an array of values, this can be achieved using the ng-init directive.
ng-repeat – This repeats a set of HTML statements for the defined number of times. The set of HTML statements will be repeated once per item in a collection. This collection must be an array or an object.
We can even create custom directives and use them in our AngularJS Application.

84. What Are Expressions In AngularJS?

Ans:

AngularJS binds data to HTML using Expressions. It can be written inside double braces: {{ expression}} or inside a directive as ng-bind=”expression”. AngularJS solves the expression and returns the result exactly where that expression is written.

AngularJS expressions are much like JavaScript expressions. They can include literals, operators, and variables.

For example –

{{ 2 + 2 }} (numbers)
{{Name + ” ” + email}} (string)
{{ Country.Name }} (object)
{{ fact[4] }} (array)

85. What Are Filters? Explain Different Filters Provided By AngularJS?

Ans:

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:

{{ bid | currency }}

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.

currency – It is used to format a number to a currency format.
date – It is required to format a date to a specified format.
filter – It chooses a subset of items from an array.
json – It formats an object to a JSON string.
limitTo – Its purpose is to create an array or string containing a specified number of elements/characters. 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.
lowercase – This filter converts a string to lower case.
number – It formats a number as text.
orderBy – It enables to sort an array. By default, sorting of strings happens alphabetically. And sorting of numbers is done numerically. It also supports a comparator function where we can define what will be counted as a match or not.
uppercase – This filter converts a string to upper case.

86. What Are Angular Prefixes $ And $?

Ans:

To prevent accidental name collisions within the code, AngularJS prefixes the names of public objects with $ and the names of private objects with $.

Use of these literals ($ or $) for any other reason is not recommended.

87. What Are Different Ways To Invoke A Directive?

Ans:

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:

<span class="my-directive: expression;"></span>

3) As an element:

<my-directive></my-directive>

4) As a comment:

<!-- directive: my-directive expression -->

88. What Is Singleton Pattern? How Does Angular Use It?

Ans:

A singleton pattern is an approach that we adopt to limit the instantiation of a Class to have only one object. In Angular, the dependency injection and the services implement the singleton pattern.

Technically, if we call the “new Class()” two times without following the singleton pattern, the outcome will be two objects of the same class. Whereas a singleton enabled class will create the object first time and return the same object onwards.

89. What Is $Scope In AngularJS?

Ans:

It is an application object. And behaves as the owner of the apps variables and functions. Scope object has access to both View and controller. Thus it works as a medium of communication between both of them. This object contains both data and functions. We can use it to access model data of the controller.

Following are the key characteristics of the scope object.

It provides observers to watch for all the model changes.
Provides the ability to propagate model changes through the application as well as outside the system to other associated components.
Scopes can be nested in such a way that they can isolate functionality and model properties.
Provides an execution environment in which expressions are evaluated.

90. What Is “$RootScope” In AngularJS?

Ans:

Every AngularJS application has a “$rootScope” that is the top-most scope created on the DOM element. An app can have only one $rootScope which will be shared among all its components. It contains the ng-app directive. Every other scope is its child scope. It can watch expressions and propagate events. Using root scope, we can set the value in one controller and read it from the other controller.


 

91. Explain The Concept Of Scope Hierarchy? How Many Scopes Can An Application Have?

Ans:

Every AngularJS application consists of one root scope but may have several child scopes. As child controllers and directives create new child scopes, they get attached to the application. These new scopes get added as children of their parent scope. Similar to DOM, they also create a hierarchical structure.

92. What Is SPA (Single Page Application) In AngularJS?

Ans:

Single-Page Applications (SPAs) are web applications that fit on a single HTML page. It dynamically updates the web page as the user performs actions on the app.

SPAs use AJAX and HTML to create quick and responsive web apps. A single page load extracts all the web app code (JS, HTML, CSS).

Thus the user navigates to different parts of the application quickly as it happens without refreshing the whole page.

The main characteristics of Single-Page Applications are as follows.

Its UI is fast and responsive. Also, the Back/Forward buttons present in the UI work properly.
IT contains more JavaScript code than actual HTML as compared to other applications.
Dynamic data loading occurs from the server-side. The API uses restful web service with JSON format.
It allows to pre-load and cache all the app pages. Thus fewer data download requests are made towards the server.
Applications written in AngularJS are cross-browser compliant. It automatically handles the JavaScript code suitable for each browser.
Even if the user has lost the internet connection, then also the SPA can work. As all the pages load in the starting itself.

93. What Is The Difference Between $Scope And Scope?

Ans:

It is mandatory to use <$scope> while defining a controller. However, the “scope” will be used to create a link function for the custom directive. Both of them refer to the “scope” object in AngularJS. The difference between them is that <$scope> uses dependency injection whereas “scope” does not.

Factory methods like controller, filter, service, etc. receive its arguments via dependency injection (DI). In DI, the order of passing the arguments does not matter. For example, a controller may be defined as (let’s set $scope as the first parameter in this case):

myApp.controller(‘MyController’, [‘$scope’, function($scope, $http) {
//rest of the code goes here }
OR ( if the $scope is the second parameter)

myApp.controller(‘MyController’, [‘$scope’, function($http, $scope) {
//rest of the code goes here }
Thus, AngularJS does not care for the position of “$scope” in both the cases. It uses the argument name to retrieve an object out of the dependency injection container.

But, in the case of directive linker function, the position of scope matters, as it does not use DI. The reason being that the supplied arguments are received by its caller. In this case, the very first parameter has to be the scope as per AngularJS syntax.

app.directive(“myDirective”, function() {
return {
scope: {};
link: function(scope, element, attrs) {
// code goes here.
}
};
});

In the case of non-dependency injected arguments, we can also give a name to injected objects. The above code can be re-written as:

app.directive(“myDirective”, function() {
return {
scope: {};
link: function(foo, bar, biz) {
// code goes here.
}
};
});

To summarize, in DI case, we pass the as <$scope> whereas, in non-DI cases, the is returned either as a scope or with any name.

94. How Is AngularJS Compiled?

Ans:

Angular’s HTML compiler allows you to teach the browser, new HTML syntax. It enables the developer to attach new behaviors or attributes to any HTML element called as directives. AngularJS compilation process takes place in the web browser itself. It does not involve any server-side or pre-compilation step.

AngularJS uses <$compiler> service to compile the angular HTML page. Its compilation begins after the HTML page (static DOM) is fully loaded.

It occurs in two phases.

Compile – It looks into the entire DOM and collects all of the directives. The result is a linking function.
Link – It combines the directives with a scope and produces a live view. Any changes in the get reflected in the view, and any operations done by the user in the view gets reflected in the .
The concept of compile and link has come from C language. Here the code is compiled first and then linked.

95. How Is AngularJS Compilation Different From Other JavaScript Frameworks?

Ans:

Javascript frameworks like backbone and jQuery process the template as a string and returns the result as a string. You have to dump this resulting 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 the data.

96. What Is Ng-View In AngularJS?

Ans:

The ng-view tag creates a placeholder where an HTML or ng-template view can be placed based on the configuration.

Let’s take an example.

<div ng-app = "testApp">
<div ng-view>
<!-- Target Html Template here -->
< /div>
</div>

In other words, ng-view is the directive that works as a container for angularJS to switch between views.

97. What Is Ng-Template In AngularJS?

Ans:

The ng-template directive is used to create an HTML view using script tag. It contains “id” attribute which is used by $routeProvider to map a view with a controller.

While defining ng-template, it is mandatory to specify the type of the 

While defining ng-template, it is mandatory to specify the type of the <script> element as the text/ng-template. Also, assign a cache name to the template using the element’s id. Later on, this name gets used as directive’s templateUrl.

Following is the syntax of using an ng-template directive in angularJS application.

<div ng-app = "mainApp"> 
<scrip t type = "text/ng-template" id = "addEmployee.htm">
<h2> Add Employee </h2>
{{message}}
</scrip t>
</div>
$routeProvider part.
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/addEmployee', {
templateUrl: 'addEmployee.htm', controller: 'AddEmployeeController'
}).
otherwise({
redirectTo: ' /addEmployee'
});
}]);

98. What Is $RouteProvider In AngularJS?

Ans:

$routeProvider is the primary service which set the configuration of URLs, map them to the corresponding HTML page or ng-template, and attach a controller with the same.

Let’s see the following example:

var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/addEmployee', {
templateUrl: 'addEmployee.htm', controller: 'AddEmployeeController'
}).
otherwise({
redirectTo: '/addEmployee'
});
}]);

Following are the important points to be considered in above example.

routeProvider is defined as a function under config of the mainApp module using a key as ‘$routeProvider.’
$routeProvider.when defines a URL “/addEmployee” which is then mapped to “addEmployee.htm”. This should be present in the same path as the main HTML page.
“otherwise” is used to set the default view.
“controller” is used to set the corresponding controller for the view.

99. What Is Data Binding? How Many Types Of Data Binding Directives Are Provided By AngularJS?

Ans:

Data binding is the connection bridge between view and business logic (view model) of the application. Data binding in AngularJs is the automatic synchronization between the model and view. When the model changes, the view is automatically updated and vice versa. AngularJs support one-way binding as well as two-way binding.

AngularJS provides the following data binding directives:

1) – It updates the text content of the specified HTML element with the value of the given expression. This text content gets updated when there is any change in the expression. It is very similar to double curly markup ( {{expression }}) but less verbose.

It has the following Syntax.

</ANY ELEMENT>
2) – It evaluates the expression and inserts the HTML content into the element in a secure way. To use this functionality, it has to use $sanitize service. For this, it is mandatory that $sanitize is available.

It has the following Syntax.

</ANY ELEMENT>
3) – It replaces the element text content with the interpolation of the template. It can contain multiple double curly markups.

It has the following Syntax.

</ANY ELEMENT>
4) – This directive informs AngularJS, not to compile or bind the contents of the current DOM element. It is useful in the case when the user wants to display the expression only and do not want to execute it.

It has the following Syntax.

</ANY ELEMENT>
5) – This directive can be bound with input, select, text area or any custom form control. It provides two-way data binding. It also provides validation behavior. It also retains the state of the control (like valid/invalid, touched/untouched and so on).

100. When To Use Factory?

Ans:

It is just a collection of functions, like a class. Hence, it can be instantiated in different controllers when you are using it with a constructor function.



 

101. Explain What String Interpolation Is In AngularJS?

Ans:

During the compilation process, AngularJS compiler matches text and attributes using interpolate service to see if it contains embedded expressions.

During normal, digest life cycle, these expressions are updated and registered as watches.

102. Explain AngularJS Application Life-Cycle?

Ans:

Understanding the life cycle of an AngularJS application makes it easier to learn about the way to design and implement the code. Apps life cycle consists of following three phases- bootstrap, compilation, and runtime.
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. After this, AngularJS initializes its necessary components and the modules to which the ng-app directive points. Now that the module has loaded, required dependencies are injected into it and become available to the code within that module.
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 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.

103. Explain AngularJS Scope Life-Cycle?

Ans:

After the angular app gets loaded into the browser, scope data passes through different stages called as its life cycle. Learning about this cycle helps us to understand the interaction between scope and other AngularJS components.

The scope data traverses through the following phases.

Creation – This phase initializes the scope. During the bootstrap process, the $injector creates the root scope of the application. And during template linking, some directives create new child scopes. A digest loop also gets created in this phase that interacts with the browser event loop. This loop is responsible for updating DOM elements with the changes made to the model as well as executing any registered watcher functions.
Watcher registration – This phase registers watchers for scope created in the above point. These watches propagate the model changes to the DOM elements, automatically. We can also register our own watcher’s on a scope by using the $watch() function.
Model mutation – This phase occurs when there is any change in the scope data. When we do any modification in the angular app code, the scope function <$apply()> updates the model and then calls the <$digest()> function to update the DOM elements and the registered watches. However, when we change the scope of the angular code like within controllers or services, angular internally calls <$apply()> function for us. But, when we do the changes to the scope outside the angular code, we have to call the <$apply()> function explicitly on the scope, to force the model and DOM to be updated correctly.
Mutation observation – This phase occurs, when the digest loop execute the $digest() function at the end of $apply() call. When the $digest() function executes, it evaluates all watches for model changes. If there is a change in the value, $digest() calls the $watch listener and updates the DOM elements.
Scope destruction – This phase occurs when the child scopes that are no longer needed, are removed from the browser’s memory by using the $destroy() function. It is the responsibility of the child scope creator to destroy them via scope.$destroy() API. This stops propagation of $digest calls into the child scopes and enables the browsers’ garbage collector to reclaim the unused memory.

104. What Is An Auto Bootstrap Process In AngularJS?

Ans:

AngularJS initializes automatically upon the “DOMContentLoaded” event or when the browser downloads the angular.js script and at the same time document.readyState is set to ‘complete.’ At this point, AngularJS looks for the ng-app directive which is the root of Angular app compilation process.

If the ng-app directive is located, then AngularJS will do the following.

  • Load the module associated with the directive.
  • Create the application injector.
  • Compile the DOM starting from the ng-app root element.
  • We term this process as Auto-bootstrapping.

105. What Is The Manual Bootstrap Process In AngularJS?

Ans:

Sometimes we may need to manually initialize Angular app to have more control over the initialization process. We can do that by using angular.bootstrap() function within angular.element(document).ready() function. AngularJS fires this function when the DOM is ready for manipulation.

The angular.bootstrap() function takes two parameters, the document, and module name injector.

106. How To Bootstrap Your Angular App For Multiple Modules?

Ans:

Bootstrap for multiple modules can be achieved by using following two methods.

1. Automatic bootstrap – AngularJS is automatically initialized for one module. When we have multiple modules, we combine them into a single module and thus the angular app will be automatically initialized to the newly created module. Other modules act as dependent modules for this newly created module.

2. Manual bootstrap – We can manually bootstrap the app by using angular.bootstrap() function, for multiple modules.




 

107. What Are Compile, Pre, And Post Linking In AngularJS?

Ans:

A) Compile – It collects an HTML string or DOM into a template and produces 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.

B) 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.

link: function LinkFn(scope, element, attr, ctrl){}
Where each of the four parameters is as follows-

Scope – It is the scope of the directive.
element – It is the DOM element where the directive has to be applied.
attr- It is the Collection of attributes of the DOM element.
ctrl – It is the array of controllers required by the directive.
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.

C) 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.

D) 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.

108. What Is A Controller In AngularJS?

Ans:

A Controller is a set of JavaScript functions which is bound to a specified scope, the ng-controller directive. Angular creates a new instance of the Controller object to inject the new scope as a dependency. The role of the Controller is to expose data to our view via $scope and add functions to it, which contains business logic to enhance view behavior.

Controller Rules.
A Controller helps in setting up the initial state of the scope object and define its behavior.
The Controller should not be used to manipulate the DOM as it contains only business logic. Instead, for managing the DOM, we should use data binding and directives.
Do not use Controllers to format input. Instead, using angular form controls is recommended for that.
Controllers should not be used to share code or states. Instead, use angular services for it.
Steps For Creating A Controller.
It needs ng-controller directive.
Next step is to add Controller code to a module.
Name your Controller based on functionality. Its name should follow camel case format (i.e., SampleController).
Set up the initial state of the scope object.
Declaring a Controller using ng-Controller directive

109. What Does Service Mean In AngularJS? Explain Its Built-In Services?

Ans:

Services are functions that are bound to perform specific tasks in an application.

It gives us a method that helps in maintaining the angular app data for its lifetime.
It gives us methods that facilitate to transfer data across the controllers in a consistent way.
It is a singleton object, and its instance is created only once per application.
It is used to organize and share, data and function across the application.
Two main execution characteristics of angular services are that they are Singleton and lazy instantiated.

1. Lazily instantiated –

It means that AngularJS instantiates a service only when a component of an application needs it. This is done by using dependency injection method, which makes the Angular codes, robust and less error-prone.

2. Singletons –

Each application component dependent on the service, work with the single instance of the service created by the AngularJS.

Let us take an example of a straightforward service that calculates the square of a given number:

var CalculationService = angular.module(‘CalculationService’, [])
.service(‘Calculation’, function () {
this.square = function (a) { return a*a};
});
AngularJS Internal Services –
AngularJS provides many built-in services. Each of them is responsible for a specific task. Built-in services are always prefixed with the $ symbol.

Some of the commonly used services in any AngularJS application are as follows:

$http – used to make an Ajax call to get the server data.
$window – Provides a reference to a DOM object.
$Location – Provides reference to the browser location.
$timeout – Provides a reference to window.set timeout function.
$Log – used for logging.
$sanitize – Used to avoid script injections and display raw HTML in the page.
$Rootscope – Used for scope hierarchy manipulation.
$Route – Used to display browser-based path in browser URL.
$Filter – Used for providing filter access.
$resource – Used to work with Restful API.
$document – Used to access the window. Document object.
$exceptionHandler – Used for handling exceptions.
$q – Provides a promise object.
$cookies – Use this service for reading, writing and deleting the browser cookies.
$parse – This service intends to convert an AngularJS expression into a function.
$cacheFactory – This service evaluates the specified expression when the user changes the input.

110. What Are Different Ways To Create Service In AngularJS?

Ans:

There are five different ways to create services in AngularJS.

Value
Factory
Service
Provider
Constant
Let’s discuss, each of the above AngularJS service types one by one with code example:

1. AngularJS Value.
It is the simplest service type supported by AngularJS that we can create and use. It is similar to a key-value pair or like a variable having a value. It can store only a single value. Let’s take an example and create a service that displays username:

var app=angular.module("app",[]);
app.value("username","Madhav");
Code to use “Value”:

We can use this service anywhere by using dependency injection. Following example injects the service in a controller:

app.controller("MainController",function($scope, username){
$scope.username=username;
});

In the above example, we have created a Value service “username” and used it in MainController.

2. AngularJS Factory.
Value service is simple to write, but they may lack many essential features. So, the next service type we will look at is “Factory” service. After its creation, we can even inject other services into it. Unlike Value service, we cannot add any dependency to it.

Let’s take an example to create a Factory service.

app.factory("username",function(){
var name="John";
return {
name:name
}
});

The above code shows that Factory service takes “function” as an argument. We can inject any number of dependencies or methods in this “function” as required by this service. This function must return some object. In our example, it returns an object with the property name. Now, let us look, as to how we can use this service:

Code to use “Factory”:

The function returns an object from service which has a property name so we can access it and use it anywhere. Let’s see how we can use it in the controller:

app.controller(“MainController”,function($scope, username){
$scope.username=username.name;
});
We are assigning the username from factory service to our scope username.

3. AngularJS Service.
It works same as the “Factory” service. But, instead of a function, it receives a Javascript class or a constructor function as an argument. Let’s take an example. Suppose we have a function:

function MyExample(num){
this.variable="value";
}

Now, we want to convert the function into a service. Let’s take a look at how we can do this with “Factory” method:

app.factory("MyExampleService",["num" ,function(num){
return new MyExample(num);
}]);

Thus in this way, we will create its new instance and return it. Also, we have injected as a dependency in Factory service. Now, let’s see how we can do this using Service type:

app.service(“MyExampleService”,[“num”, MyExample]);
Thus, we have called the service method on the module and provided its name, dependency, and the name of the function in an array.

4. AngularJS Provider.
It is the parent of all the service types supported by AngularJS, except the “Constant” that we will discuss in the next section. It is the core of all the service types. Thus we can say that other services work on top of it. It allows us to create a configurable service that must implement the <$get> method.

We use this service to expose the API that is responsible for doing the application-wide configuration. The configuration should complete before starting the application.

Let’s take an example.

app.provider('authentication', function() {
var username = "John";
return {
set: function(newUserName) {
username = newUserName;
},
$get: function() {
function getUserName() {
return username;
}
return {
getUserName: getUserName
};
}
};
});

This example initializes a provider with its name as “authentication.” It also implements a <$get> function, which returns a method “getUsername” which in turn returns the private variable called username. This also has a setter, using it we can set the username on application startup as follows:

app.config(["authenticationProvider", function(authenticationProvider) {
authenticationProvider.set("Mihir");
}]);

5. AngularJS Constant.
As the name suggests, this service helps us to declare constants in our application. We can then use them wherever needed, just by adding it as a dependency. There are many places, where we use constants like some base URLs, application name, etc.

We just define them once and use them anywhere as per our need. Thus, this technique allows us to write the definition in one place. If there is any change in the value later, we have to do the modifications at one place only.

Here is an example of how we can create constants:

app.constant('applicationName', 'Service Tutorials');

111. What Is The Difference Between The $Watch, $Digest, And $Apply?

Ans:

In AngularJS $scope object is having different functions like $watch(), $digest() and $apply() and we will call these functions as central functions. The AngularJS central functions $watch(), $digest(), and $apply() are used to bind data to variables in view and observe changes happening in variables.

A) $Watch() –
The use of this function is to observe changes in a variable on the $scope. It triggers a function call when the value of that variable changes. It accepts three parameters: expression, listener, and equality object. Here, listener and equality objects are optional parameters.

$watch(watchExpression, listener, [objectEquality]).

B) $Digest() –
This function iterates through all the watch list items in the $scope object, and its child objects (if it has any). When $digest() iterates over the watches, it checks if the value of the expression has changed or not. If the value has changed, AngularJS calls the listener with the new value and the old value.

The $digest() function is called whenever AngularJS thinks it is necessary. For example, after a button click, or after an AJAX call. You may have some cases where AngularJS does not call the $digest() function for you. In that case, you have to call it yourself.

 

C) $Apply() –
AngularJS automatically updates the model changes which are inside AngularJS context. When you apply changes to any model, that lies outside of the Angular context (like browser DOM events, setTimeout, XHR or third-party libraries), then you need to inform the Angular about the changes by calling $apply() manually. When the $apply() function call finishes, AngularJS calls $digest() internally, to update all data bindings.

Following are the key differences between $apply() and $digest().

Its use is to update the model properties forcibly.
The $digest() method evaluates the watchers for the current scope. However, the $apply() method is used to evaluate watchers for root scope, that means it’s for all scopes.

 

112. Which One Handles Exception Automatically Between $Digest And $Apply?

Ans:

When an error occurs in one of the watchers, $digest() cannot handle them via $exceptionHandler service. In that case, you have to manage the exception yourself. However, $apply() uses try catch block internally to handle errors. But, if an error occurs in one of the watchers, then it transfers the errors to $exceptionHandler service.

Code for $apply() function.

$apply(expr) { 
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}

113. Explain $Watch(), $Watchgroup() And $WatchCollection() Functions Of Scope?

Ans:

A) $Watch.
Its use is to observe the changes in the variable on the $scope. It accepts three arguments – expression, listener, and equality object. The listener and Equality object are optional parameters.

$watch(watchExpression, listener, [objectEquality])
Here, is the expression to be observed in the scope. This expression gets called on every $digest() and returns a value for the listener to monitor.

The listener defines a function which gets called when watchExpression changes its value. In case, its value does not change then the listener will not be called. The objectEquality is a boolean type to compare the objects for equality using angular.equals.

scope.name = 'shailendra'; 
scope.counter = 0;
scope.$watch('name', function (newVal, oldVal) {
scope.counter = scope.counter + 1; });

B) $Watchgroup.
This function was introduced in Angular 1.3. It works in the same way as $watch() function except that the first parameter is an array of expressions.

$watchGroup(watchExpression, listener)
The listener is also an array containing the new and old values of the variables that are being watched. The listener gets called whenever any expression contained in the watchExpressions array changes.

$scope.teamScore = 0; 
$scope.time = 0;
$scope.$watchGroup(['teamScore', 'time'], function(newVal, oldVal) {
if(newVal[0] > 20){
$scope.matchStatus = 'win';
}
else if (newVal[1] > 60){
$scope.matchStatus = 'times up';
});

C) $WatchCollection.
This use of this function is to watch the properties of an object. It gets fired when there is any change in the properties. It takes an object as the first parameter and watches the properties of the object.

$watchCollection(obj, listener)
The listener is called whenever there is any change in the obj.

$scope.names = [‘shailendra’, ‘deepak’, ‘mohit’, ‘kapil’];
$scope.dataCount = 4;
$scope.$watchCollection(‘names’, function (newVal, oldVal) {
$scope.dataCount = newVal.length;
});

114. What Are The Form Validations Supported By AngularJS?

Ans:

AngularJS allows form validation on the client-side in a simplistic way. First of all, it monitors the state of the form and its input fields. Secondly, it observes any change in the values and notifies the same to the user.
Let’s discuss the different input field validations along with examples.

A) Required Field Validation.
By using “Required Field” validation we can prevent, form submission with a null value. It’s mandatory for the user to fill the form fields.

B) Minimum & Maximum Field Length Validations.
To prevent the user from providing less or excess number of characters in the input field, we use Minimum & Maximum length validation. The AngularJS directive used for Minimum & Maximum length validations are and . Both of these attributes take integer values. The attribute is used to set the number of characters a user is limited to, whereas the attribute sets the maximum number of characters that a user is allowed to enter.

C) Matches Pattern Validation.
AngularJS provides an directive to ensure that input fields match the regular expressions that are passed into the attribute.

D) Email Validation.
To validate an email id, AngularJS provides ng-model directive.

E) Number Validation.

To validate input against Number we can use ng-model directive from AngularJS.

F) URL Validation.
To validate an input field for URL.

 
 

115. How Do You Exchange Data Among Different Modules Of Your Angular JS Application?

Ans:

There are a no. of ways in Angular to share data among modules. A few of them are as follows.

The most common method is to create an Angular service to hold the data and dispatch it to the modules.
Angular has a matured event system which provides $broadcast(), $emit() and $on() methods to raise events and pass data among the controllers.
We can also use $parent, $nextSibling, and $ controllerAs to directly access the controllers.
Variables defined at the root scope level ($rootScope) are available to the controller scope via prototypical inheritance. But they behave like globals and hard to maintain.

116. How Would You Use An Angular Service To Pass Data Between Controllers? Explain With Examples?

Ans:

Using services is the best practice in Angular to share data between controllers. Here is a step by step example to demonstrate data transfer.

We can prepare the data service provider in the following manner.

app.service('dataService', function() {
var dataSet = [];
var addData = function(newData) {
dataSet.push(newData);
};
var getData = function(){
return dataSet;
};
return {
addData: addData,
getData: getData
};
});

Now, we’ll inject the service dependency into the controllers.

Say, we have two controllers – pushController and popController.

The first one will add data by using the data service provider’s addData method. And the latter will fetch this data using the service provider’s getData method.

app.controller('pushController', function($scope, dataService) {
$scope.callToAddToProductList = function(currObj){
dataService.addData(currObj);
};
});
app.controller('popController', function($scope, dataService) {
$scope.dataSet = dataService.getData();
});

 

117. How Will You Send And Receive Data Using The Angular Event System? Use Methods Like $Broadcast And $On To Send Data Across?

Ans:

We can call the $broadcast method using the $rootScope object and send any data we want.

$scope.sendData = function() {

$rootScope.$broadcast(‘send-data-event’, data);
}
To receive data, we can use the $scope object inside a controller.

$scope.$on(‘send-data-event’, function(event, data) {

// process the data.
});