Angularjs Interview Questions
1) What is Angular.js?
AngularJS is a javascript framework used for creating single web page applications. It allows you to use HTML as your template language and enables you to extend HTML’s syntax to express your application’s components clearly
2) Explain what are the key features of Angular.js ?
The key features of angular.js are
- Scope
- Controller
- Model
- View
- Services
- Data Binding
- Directives
- Filters
- Testable
3) Explain what is scope in Angular.js ?
Scope refers to the application model, it acts like glue between application controller and the view. Scopes are arranged in hierarchical structure and impersonate the DOM ( Document Object Model) structure of the application. It can watch expressions and propagate events.
4) Explain what is services in Angular.js ?
In angular.js services are the singleton objects or functions that are used for carrying out specific tasks. It holds some business logic and these function can be called as controllers, directive, filters and so on.
5) Explain what is Angular Expression? Explain what is key difference between angular expressions and JavaScript expressions?
Like JavaScript, Angular expressions are code snippets that are usually placed in binding such as {{ expression }}
The key difference between the JavaScript expressions and Angular expressions
- Context : In Angular, the expressions are evaluated against a scope object, while the Javascript expressions are evaluated against the global window
- Forgiving: In Angular expression evaluation is forgiving to null and undefined, while in Javascript undefined properties generates TypeError or ReferenceError
- No Control Flow Statements: Loops, conditionals or exceptions cannot be used in an angular expression
- Filters: To format data before displaying it you can use filters
6) With options on page load how you can initialize a select box ?
You can initialize a select box with options on page load by using ng-init directive
- <div ng-controller = “ apps/dashboard/account ” ng-switch
- On = “! ! accounts” ng-init = “ loadData ( ) ”>
7) Explain what are directives ? Mention some of the most commonly used directives in Angular.js application ?
A directive is something that introduces new syntax, they are like markers on DOM element which attaches a special behavior to it. In any Angular.js application, directives are the most important components.
Some of the commonly used directives are ng-model, ng-App, ng-bind, ng-repeat , ng-show etc.
8) Mention what are the advantages of using Angular.js ?
Angular.js has several advantages in web development.
- Angular.js supports MVS pattern
- Can do two ways data binding using Angular.js
- It has per-defined form validations
- It supports both client server communication
- It supports animations
9) Explain what Angular JS routes does ?
Angular js routes enable you to create different URLs for different content in your application. Different URLs for different content enables user to bookmark URLs to specific content. Each such bookmarkable URL in Angular.js is called a route
A value in Angular JS is a simple object. It can be a number, string or JavaScript object. Values are typically used as configuration injected into factories, services or controllers. A value should be belong to an Angular.js module.
Injecting a value into an Angular.js controller function is done by adding a parameter with the same name as the value
10) Explain what is data binding in Angular.js ?
Automatic synchronization of data between the model and view components is referred as data binding in Angular.js. There are two ways for data binding
- Data mining in classical template systems
- Data binding in angular templates
11) What makes angular.js better ?
- Registering Callbacks: There is no need to register callbacks . This makes your code simple and easy to debug.
- Control HTML DOM programmatically: All the application that are created using Angular never have to manipulate the DOM although it can be done if it is required
- Transfer data to and from the UI: Angular.js helps to eliminate almost all of the boiler plate like validating the form, displaying validation errors, returning to an internal model and so on which occurs due to flow of marshalling data
- No initilization code: With angular.js you can bootstrap your app easily using services, which auto-injected into your application in Guice like dependency injection style
12) Explain what is string interpolation in angular.js ?
In angular.js the compiler during the compilation process matches text and attributes using interpolate service to see if they contains embedded expressions. As part of normal digest cycle these expressions are updated and registered as watches.
13) Mention the steps for the compilation process of HTML happens?
Compilation of HTML process occurs in following ways
- Using the standard browser API, first the HTML is parsed into DOM
- By using the call to the $compile () method, compilation of the DOM is performed. The method traverses the DOM and matches the directives.
- Link the template with scope by calling the linking function returned from the previous step
14) Explain what is directive and Mention what are the different types of Directive?
During compilation process when specific HTML constructs are encountered a behaviour or function is triggered, this function is referred as directive. It is executed when the compiler encounters it in the DOM.
Different types of directives are
- Element directives
- Attribute directives
- CSS class directives
- Comment directives
15) Explain what is linking function and type of linking function?
Link combines the directives with a scope and produce a live view. For registering DOM listeners as well as updating the DOM, link function is responsible. After the template is cloned it is executed.
- 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
16) Explain what is injector?
An injector is a service locator. It is used to retrieve object instances as defined by provider, instantiate types, invoke methods and load modules. There is a single injector per Angular application, it helps to look up an object instance by its name.
17) Explain what is the difference between link and compile in angular.js?
- Compile function: It is used for template DOM Manipulation and collect all of the directives.
- Link function: It is used for registering DOM listeners as well as instance DOM manipulation. It is executed once the template has been cloned.
18) Explain what is factory method in angular.js?
For creating the directive, factory method is used. It is invoked only once, when compiler matches the directive for the first time. By using $injector.invoke the factory method is invoked.
19) Mention what are the styling form that ngModel adds to CSS classes ?
ngModel adds these CSS classes to allow styling of form as well as control
- ng- valid
- ng- invalid
- ng-pristine
- ng-dirty
20) Mention what are the characteristics of “Scope”?
- To observer model mutations scopes provide APIs ($watch)
- To propagate any model changes through the system into the view from outside of the Angular realm
- A scope inherits properties from its parent scope, while providing access to shared model properties, scopes can be nested to isolate application components
- Scope provides context against which expressions are evaluated
21) Explain what is DI (Dependency Injection ) and how an object or function can get a hold of its dependencies ?
DI or Dependency Injection is a software design pattern that deals with how code gets hold of its dependencies. In order to retrieve elements of the application which is required to be configured when module gets loaded , the operation “config” uses dependency injection.
These are the ways that object uses to hold of its dependencies
- Typically using the new operator, dependency can be created
- By referring to a global variable, dependency can be looked up
- Dependency can be passed into where it is required
22) Mention what are the advantages of using Angular.js framework ?
Advantages of using Angular.js as framework are
- Supports two way 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
23) Explain the concept of scope hierarchy? How many scope can an application have?
Each angular application consist of one root scope but may have several child scopes. As child controllers and some directives create new child scopes, application can have multiple scopes. When new scopes are formed or created they are added as a children of their parent scope. Similar to DOM, they also creates a hierarchical structure.
24) Explain what is the difference between angular.js and backbone.js?
Angular.js combines the functionalities of most of the 3rd party libraries, it supports individual functionalities required to develop HTML5 Apps. While Backbone.js do their jobs individually.
25) Who created Angular JS ?
Intially it was developed by Misko Hevery and Adam Abrons. Currently it is being developed by Google
Angular Interview questions and answers
AngularJS is one of those hot topics which interviewer’s ask for Web programming. In this article we will run through some important Interview questions around AngularJS and how we should be go about answering the same.
Do not forget to see our Learn MVC with Angular in 2 days i.e. ( 16 hours ) video series. Start from this youtube video link. https://www.youtube.com/watch?v=Lp7nSImO5vk
What is AngularJS ?
“AngularJS is a JavaScript framework which simplifies binding JavaScript objects with HTML UI elements.”
Let us try to understand the above definition with simple sample code.
Below is a simple “Customer” function with “CustomerName” property. We have also created an object called as “Cust” which is of “Customer” class type.
Hide Copy Code
function Customer()
{
this.CustomerName = "AngularInterview";
}
var Cust = new Customer();
Now let us say the above customer object we want to bind to a HTML text box called as “TxtCustomerName”. In other words when we change something in the HTML text box the customer object should get updated and when something is changed internally in the customer object the UI should get updated.
Hide Copy Code
<input type=text id="TxtCustomerName" onchange="UitoObject()"/>
So in order to achieve this communication between UI to object developers end up writing functions as shown below. “UitoObject” function takes data from UI and sets it to the object while the other function “ObjecttoUI” takes data from the object and sets it to UI.
Hide Copy Code
function UitoObject()
{
Cust.CustomerName = $("#TxtCustomerName").val();
}
function ObjecttoUi()
{
$("#TxtCustomerName").val(Cust.CustomerName);
}
So if we analyze the above code visually it looks something as shown below. Your both functions are nothing but binding code logic which transfers data from UI to object and vice versa.

Now the same above code can be written in Angular as shown below. The javascript class is attached to a HTML parent div tag using “ng-controller” directive and the properties are binded directly to the text box using “ng-model” declarative.
So now whatever you type in the textbox updates the “Customer” object and when the “Customer” object gets updated it also updates the UI.
Hide Copy Code
<div ng-controller="Customer"> <input type=text id="txtCustomerName" ng-model="CustomerName"/> </div>
In short if you now analyze the above code visually you end up with something as shown in the below figure.You have the VIEW which is in HTML, your MODEL objects which are javascript functions and the binding code in Angular.

Now that binding code have different vocabularies.
- Some developers called it “ViewModel” because it connects the “Model” and the “View” .
- Some call it “Presenter” because this logic is nothing but presentation logic.
- Some term it has “Controller” because it controls how the view and the model will communicate.
To avoid this vocabulary confusion Angular team has termed this code as “Whatever”. It’s that “Whatever” code which binds the UI and the Model. That’s why you will hear lot of developers saying Angular implements “MVW” architecture.
Explain Directives in Angular?
Directives are attributes decorated on the HTML elements. All directives start with the word “ng”. As the name says directive it directs Angular what to do.
For example below is a simple “ng-model” directive which tells angular that the HTML textbox “txtCustomerName” has to be binded with the “CustomerName” property.
Hide Copy Code
<input type=text id="txtCustomerName" ng-model="CustomerName"/>
Some of the most commonly used directives are ng-app,ng-controller and ng-repeat.
What are controllers and need of ng-controller and ng-model in Angular?
“Controllers” are simple javascript function which provides data and logic to HTML UI. As the name says controller they control how data flows from the server to HTML UI.

For example below is simple “Customer” controller which provides data via “CustomerName” and “CustomerCode” property and Add/ Update logic to save the data to database.
| Note: - Do not worry too much about the $scope , we will discuss the same in the next question. |
Hide Copy Code
function Customer($scope)
{
$scope.CustomerName = "Shiv";
$scope.CustomerCode = "1001";
$scope.Add = function () {
}
$scope.Update = function () {
}
}
“ng-controller” is a directive.Controllers are attached to the HTML UI by using the “ng-controller” directive tag and the properties of the controller are attached by using “ng-model” directive. For example below is a simple HTML UI which is attached to the “Customer” controller via the “ng-controller” directive and the properties are binded using “ng-model” directive.
Hide Copy Code
<div ng-controller="Customer"> <input type=text id="CustomerName" ng-model="CustomerName"/><br /> <input type=text id="CustomerCode" ng-model="CustomerCode"/> </div>
What are expressions in Angular?
Angular expressionsare unit of code which resolves to value. This code is written inside curly braces “{“.
Below are some examples of angular expressions:-
The below expression adds two constant values.
Hide Copy Code
{{1+1}}
The below expression multiplies quantity and cost to get the total value.
Hide Copy Code
The value total cost is {{ quantity * cost }}
The below expression displays a controller scoped variable.
Hide Copy Code
<div ng-controller="CustomerVM"> The value of Customer code is {{CustomerCode}} </div>
The value of Customer code is {{CustomerCode}}
How can we initialize Angular application data?
We can use “ng-init” directive to achieve the same. You can see in the below example we have used “ng-init” directive to initialize the “pi” value.
Hide Copy Code
<body ng-app="myApp" ng-init="pi=3.14"> The value of pi is {{pi}} </body>
Explain $scope in Angular?
“$scope” is an object instance of a controller. “$scope” object instance get’s created when “ng-controller” directive is encountered.
For example in the below code snippet we have two controllers “Function1” and “Function2”. In both the controllers we have a “ControllerName” variable.
Hide Copy Code
function Function1($scope)
{
$scope.ControllerName = "Function1";
}
function Function2($scope)
{
$scope.ControllerName = "Function2";
}
Now to attach the above controllers to HTML UI we need to use “ng-controller” directive. For instance you can see in the below code snippet how “ng-controller” directive attaches “function1” with “div1” tag and “function2” with “div2” tag.
Hide Copy Code
<div id=”div1” ng-controller="Function1"> Instance of {{ControllerName}} created </div> <div id=”div2” ng-controller="Function2"> Instance of {{ControllerName}} created </div>
So this is what happens internally. Once the HTML DOM is created Angular parser starts running on the DOM and following are the sequence of events:-
- The parser first finds “ng-controller” directive which is pointing to “Function1”. He creates a new instance of “$scope” object and connects to the “div1” UI.
- The parser then starts moving ahead and encounters one more “ng-controller” directive which is pointing to “Function2”. He creates a new instance of “$scope” object and connects to the “div2” UI.

Now once the instances are created, below is a graphical representation of the same. So the “DIV1” HTML UI is binded with “function1” $scope instance and the “DIV2” HTML UI is binded with “function2” $scope instance. In other words now anything changes in the $scope object the UI will be updated and any change in the UI will update the respective $scope object.

What is “$rootScope” and how is it related with “$scope”?
“$rootScope” is a parent object of all “$scope” angular objects created in a web page.

Let us understand how Angular does the same internally. Below is a simple Angular code which has multiple “DIV” tags and every tag is attached to a controller. So let us understand step by step how angular will parse this and how the “$rootScope” and “$scope” hierarchy is created.

The Browser first loads the above HTML page and creates a DOM (Document object model) and Angular runs over the DOM.Below are the steps how Angular creates the rootscope and scope objects.
- Step 1:- Angular parser first encounters the “ng-app” directive and creates a “$rootScope” object in memory.
- Step 2:- Angular parser moves ahead and finds the expression {{SomeValue}}. It creates a variable
- Step 3:- Parser then finds the first “DIV” tag with “ng-controller” directive which is pointing to “Function1” controller. Looking at the “ng-controller” directive it creates a “$scope” object instance for “Function1” controller. This object it then attaches to “$rootScope” object.
- Step 4:- Step 3 is then repeated by the parser every time it finds a “ng-controller” directive tag. Step 5 and Step 6 is the repetition of Step 3.
If you want to test the above fundamentals you can run the below sample Angular code. In the below sample code we have created controllers “Function1” and “Function2”. We have two counter variables one at the root scope level and other at the local controller level.
Hide Copy Code
<script language="javascript">
function Function1($scope, $rootScope)
{
$rootScope.Counter = (($rootScope.Counter || 0) + 1);
$scope.Counter = $rootScope.Counter;
$scope.ControllerName = "Function1";
}
function Function2($scope, $rootScope)
{
$rootScope.Counter = (($rootScope.Counter || 0) + 1);
$scope.ControllerName = "Function2";
}
var app = angular.module("myApp", []); // creating a APP
app.controller("Function1", Function1); // Registering the VM
app.controller("Function2", Function2);
</script>
Below is the HTML code for the same. You can we have attached “Function1” and “Function2” two times with “ng-controller” which means four instances will be created.
Hide Copy Code
<body ng-app="myApp" id=1> Global value is {{Counter}}<br /> <div ng-controller="Function1"> Child Instance of {{ControllerName}} created :- {{Counter}} </div><br /> <div ng-controller="Function2"> Child Instance of {{ControllerName}} created :- {{Counter}} </div><br /> <div ng-controller="Function1"> Child Instance of {{ControllerName}} created :- {{Counter}} </div><br /> <div ng-controller="Function2"> Child Instance of {{ControllerName}} created :- {{Counter}} </div><br /> </body>

Above is the output of the code you can see the global variable of root scope has be incremented four times because four instances of $scope have been created inside “$rootScope” object.
Do I need Jquery for Angular?
No , you do not need Jquery for Angular. It’s independent of Jquery.
How is the data binding in Angular ?
Its two way binding. So whenever you make changes in one entity the other entity also gets updated.
How do we make HTTP get and post calls in Angular?
To make HTTP calls we need to use the “$http” service of Angular. In order to use the http services you need to make provide the “$http” as a input in your function parameters as shown in the below code.
Hide Copy Code
function CustomerController($scope,$http)
{
$scope.Add = function()
{
$http({ method: "GET", url: "http://localhost:8438/SomeMethod" }).success(function (data, status, headers, config)
{
// Here goes code after success
}
}
}
“$http” service API needs atleast three things:-
- First what is the kind of call “POST” or “GET”.
- Second the resource URL on which the action should happen.
- Third we need to define the “success” function which will be executed once we get the response from the server.
Hide Copy Code
$http({ method: "GET", url: "http://localhost:8438/SomeMethod" }).success(function (data, status, headers, config)
{
// Here goes code after success
}
How do we pass data using HTTP POST in Angular ?
You need to pass data using the “data” keyword in the “$http” service API function. In the below code you can see we have created a javascript object “myData” with “CustomerName” property. This object is passed in the “$http” function using HTTP POST method.
Hide Copy Code
Var myData = {};
myData.CustomerName = “Test”;
$http({ method: "POST",
data: myData,
url: "http://www.xyz.com"})
.success(function (data, status, headers, config)
{
// Here goes code after success
}
What is dependency injection and how does it work in Angular?
Dependency injection is a process where we inject the dependent objects rather than consumer creating the objects. DI is everywhere in Angular or we can go one step ahead and say Angular cannot work without DI.
For example in the below code “$scope” and “$http” objects are created and injected by the angular framework. The consumer i.e. “CustomerController” does not create these objects himself rather Angular injects these objects.
Hide Copy Code
function CustomerController($scope,$http)
{
// your consumer would be using the scope and http objects
}
How does DI benefit in Angular?
There are two big benefits of DI: - Decoupling and Testing.
Let’s first start with Decoupling. Consider your application has a logger functionality which helps to log errors , warning etc in some central place. This central place can be a file, event viewer, database etc.
Hide Copy Code
function FileLogger()
{
this.Log = function () {
alert("File logger");
};
}
function EventLogger()
{
this.Log = function () {
alert("Event viewer logger");
};
}
Now let’s say you have a “Customer” class who wants to use the “Logger” classes. Now which “Logger” class to use depends on configuration.

So the code of “Customer” is something as shown below. So depending on the configuration “Customer” class either creates “FileLogger” or it creates “EventLogger” object.
Hide Copy Code
function Customer($scope, Logger)
{
$scope.Logger = {};
if (config.Loggertype = "File")
{
$scope.Logger = new FileLogger();
}
else
{
$scope.Logger = new EventLogger();
}
}
But with DI our code becomes something as shown below. The “Customer” class says he is not worried from where the “Logger” object comes and which type of “Logger” objects are needed .He just wants to use the “Logger” object.
Hide Copy Code
function Customer($scope,$http, Logger)
{
$scope.Logger = Logger;
}
With this approach when a new “Logger” object gets added the “Customer” class does not have to worry about the new changes because the dependent objects are injected by some other system.
The second benefit of DI is testing. Let’s say you want to test the “Customer” class and you do not have internet connection. So your “$http” object method calls can throw errors. But now you can mock a fake “$http” object and run your customer class offline without errors.The fake object is injected using DI.
The second benefit of DI is testing. Let’s say you want to test the “Customer” class and you do not have internet connection. So your “$http” object method calls can throw errors. But now you can mock a fake “$http” object and run your customer class offline without errors.The fake object is injected using DI.
What are services in Angular?
Service helps to implement dependency injection. For instance let’s say we have the below “Customer” class who needs “Logger” object. Now “Logger” object can be of “FileLogger” type or “EventLogger” type.
Hide Copy Code
function Customer($scope,$http, Logger)
{
$scope.Logger = Logger;
}
So you can use the “service” method of the application and tie up the “EventLogger” object with the “Logger” input parameter of the “Customer” class.
Hide Copy Code
var app = angular.module("myApp", []); // creating a APP
app.controller("Customer", Customer); // Registering the VM
app.service("Logger", EventLogger); // Injects a global Event logger object
So when the controller object is created the “EventLogger” object is injected automatically in the controller class.
Are Service object instances global or local?
Angular Services create and inject global instances. For example below is a simple “HitCounter” class which has a “Hit” function and this function increments the variable count internally every time you call hit the button.
Hide Copy Code
function HitCounter()
{
var i = 0;
this.Hit = function ()
{
i++;
alert(i);
};
}
This “HitCounter” class object is injected in “MyClass” class as shown in the below code.
Hide Copy Code
function MyClass($scope, HitCounter)
{
$scope.HitCounter = HitCounter;
}
Below code advises the Angular framework to inject “HitCounter” class instance in the “MyClass” class. Read the last line of the below code specially which says to inject the inject the “HitCounter” instance.
Hide Copy Code
var app = angular.module("myApp", []); // creating a APP
app.controller("MyClass", MyClass); // Registering the VM
app.service("HitCounter", HitCounter); // Injects the object
Now let’s say that the “Controller” “MyClass” is attached to twodiv tag’s as shown in the below figure.
So two instances of “MyClass” will be created. When the first instance of “MyClass” is created a “HitCounter” object instance is created and injected in to “MyClass” first instance.
When the second instance of “MyClass” is created the same “HitCounter” object instance is injected in to second instance of “MyClass”.
Again I repeat the same instance is injected in to the second instance, new instances are not created.
Again I repeat the same instance is injected in to the second instance, new instances are not created.

If you execute the above code you will see counter values getting incremented even if you are coming through different controller instances.
What is a Factory in Angular?
“Factory” in real world means a premise where products are manufactured. Let’s take an example of a computer manufacturing firm. Now the company produces different kinds and sizes of computers likelaptops,desktops, tablets etc.
Now the process of manufacturing the computer products are same with slight variation. To manufacture any computer we need processor, RAM and hard disk. But depending on what kind of final case packing is the final product shapes.

That’s what the use of Factory in Angular.
For example see the below code we have a “Customer”, “Phone” and “Address” class.
Hide Copy Code
function Customer()
{
this.CustomerCode = "1001";
this.CustomerName = "Shiv";
}
function Phone()
{
this.PhoneNumber = "";
}
function Address()
{
this.Address1 = "";
this.Address2 = "";
}
So now we would create different types of “Customer” object types using the combination of “Address” and “Phones” object.
- We would like to combine “Customer” with “Address” and create a “Customer” object which has “Address” collection inside it.
- Or must be we would like to create “Customer” object with “Phone” objects inside it.
- Or must be “Customer” object with both “Phone” and “Address” objects.

In other words we would like to have different permutation and combination to create different types of “Customer” objects.
So let’s start from bottom. Let’s create two factory function’s one which creates “Address” object and the other which creates “Phone” objects.
Hide Copy Code
functionCreateAddress()
{
var add = new Address();
return add;
}
functionCreatePhone()
{
var phone = new Phone();
return phone;
}
Now let’s create a main factory function which uses the above two small factory functions and gives us all the necessary permutation and combination.
In the below factory you can see we have three functions:-
- “CreateWithAddress” which creates “Customer” with “Address” objects inside it.
- “CreateWithPhone” which creates “Customer” object with “Phone” objects inside it.
- “CreateWithPhoneAddress” which creates “Customer” object with aggregated “Phone” and “Address” objects.
Hide Copy Code
function CreateCustomer() {
return {
CreateWithAddress: function () {
varcust = new Customer();
cust.Address = CreateAddress();
returncust;
},
CreateWithPhone: function () {
varcust = new Customer();
cust.Phone = {};
cust.Phone = CreatePhone();
returncust;
}
,
CreateWithPhoneAddress: function () {
debugger;
varcust = new Customer();
cust.Phone = CreatePhone();
cust.Address = CreateAddress();
returncust;
}
}
}
Below is a simple “CustomerController” which takes “CustomerFactory” as the input. Depending on “TypeOfCustomer” it creates with “Address” , “Phones” or both of them.
Hide Copy Code
functionCustomerController($scope, Customerfactory)
{
$scope.Customer = {};
$scope.Init = function(TypeofCustomer)
{
if (TypeofCustomer == "1")
{
$scope.Customer = Customerfactory.CreateWithAddress();
}
if (TypeofCustomer == "2")
{
$scope.Customer = Customerfactory.CreateWithPhone();
}
if (TypeofCustomer == "3") {
$scope.Customer = Customerfactory.CreateWithPhoneAddress();
}
}
}
You also need to tell Angular that the “CreateCustomer” method needs to be passed in the input. For that we need to call the “Factory” method and map the “CreateCustomer” method with the input parameter “CustomerFactory” for dependency injection.
Hide Copy Code
var app = angular.module("myApp", []); // creating a APP
app.controller("CustomerController", CustomerController); // Register the VM
app.factory("Customerfactory", CreateCustomer);
So if we consume the “CustomerController” in UI , depending on situation it creates different flavors of “Customer” object. You can in the below code we have three different “DIV” tags and depending on the “TypeofCustomer” we are displaying data.

What is the difference between Factory and Service?
“Factory” and “Service” are different ways of doing DI (Dependency injection) in angular. Please read the previous question to understand what is DI.
So when we define DI using “service” as shown in the code below. This creates a new GLOBAL instance of the “Logger” object and injects it in to the function.
Hide Copy Code
app.service("Logger", Logger); // Injects a global object
When you define DI using a “factory” it does not create a instance. It just passes the method and later the consumer internally has to make calls to the factory for object instances.
Hide Copy Code
app.factory("Customerfactory", CreateCustomer);
Below is a simple image which shows visually how DI process for “Service” is different than “Factory”.

| Factory | Service | |
| Usage | When we want to create different types of objects depending on scenarios. For example depending on scenario we want to create a simple “Customer” object , or “Customer” with “Address” object or “Customer” with “Phone” object. See the previous question for more detailed understanding. | When we have utility or shared functions to be injected like Utility , Logger , Error handler etc. |
| Instance | No Instance created. A method pointer is passed. | Global and Shared instance is created. |
How are validations implemented in Angular?
Angular leverages HTML 5 validations and new form element types to implement validation.

For instance below is a simple form which has two text boxes. We have used HTML 5 “required” validation attribute and a form element of type “email”.
Hide Copy Code
<form name="frm1" id="frm1" > Name :- <input type=text name="CustomerName" id="CustomerName" required /> Email :- <input type=email name="Email" id="Email" /> <input type=submit value="Click here"/> </form>
Below are some example of new form elements introduced in HTML 5 and Angular works with almost all of them :-
- Color.
- Date
- Datetime-local
- Time
- Url
- Range
- Telephone
- Number
- Search
When you run the above HTML inside a browser which understands HTML 5 , you will see your validations and form types in actions as shown in the below browser screen shot.

Angular leverages HTML 5 validation attributes and new HTML 5 form elements. Now if we want Angular to handle validation we need first stop HTML 5 to do validation. So for that the first step is to specify “novalidate” attribute on the form tag.
Hide Copy Code
<form name="frm1" novalidate> ----- </form>
So now the HTML will not fire those validations it will be routed to the Angular engine to further take actions.
In other words when end user fills data in the HTML UI , validation events are routed to Angular framework and depending on scenario Angular sets a field called as “$Valid”. So if the validations are fine it sets it to “True” or else its sets it to “False”.

So you can see in the below code we have attached the angular controller and models to the text boxes. Watch the code of the button it has “ng-disabled” attribute which is set via the “$Valid” property in a NEGATED fashion.
Negated fashion means when there is no error it should enable the button and when there are errors that means it’s false it should disable the button.
Hide Copy Code
<form name="frm1" novalidate> Name:-<input type=text ng-model="Customer.CustomerName" name="CustomerName" required /> Email :- <input type=email ng-model="Customer.Email" name="Email" /> <input type=submit value="Click here" ng-disabled="!(frm1.$valid)"/> </form>
Note :- “Name” is needed for the validations to work.
How to check error validation for a specific field?
To check for a specific field you need to use the below DOM code.
Hide Copy Code
!frm1.CustomerName.$valid
What does SPA (Single page application) mean?
SPA is a concept where rather loading pages from the server by doing post backs we create a single shell page or master page and load the webpages inside that master page.
How can we implement SPA with Angular?
By using Angular routes.
How to implement routing in Angular?
Implementing Angular route is a five step process: -
Step 1: - Add the “Angular-route.js” file to your view.
Hide Copy Code
<script src="~/Scripts/angular-route.js"></script>
Step 2: - Inject “ngroute” functionality while creating Angular app object.
Hide Copy Code
var app = angular.module("myApp", ['ngRoute']);
Step 3: - Configure the route provider.
In route provider we need to define which URL pattern will load which view. For instance in the below code we are saying “Home” loads “Yoursite/Home” view and “Search” loads “YourSite/Search” view.
Hide Copy Code
app.config(['$routeProvider',
function ($routeProvider) {;
$routeProvider.
when('/Home, {
templateUrl: 'Yoursite/Home',
controller: 'HomeController'
}).
when('/Search', {
templateUrl: YourSite/Search',
controller: 'SearchController'
}).
otherwise({
redirectTo: '/'
});
}]);
Step 4: - Define hyperlinks.
Define hyper link with the “#” structure as shown below. So now when user clicks on the below anchor hyperlinks, these actions are forwarded to route provider and router provider loads the view accordingly.
Hide Copy Code
Step 5: - Define sections where to load the view.
Once the action comes to the router provider it needs a place holder to load views. That’s defined by using the “ng-view” tag on a HTML element. You can see in the below code we have created a “DIV” tag with a place holder. So the view will load in this section.
Hide Copy Code
So if we summarize angular routing is a three step process (Below is a visual diagram for the same): -
- Step 1: - End user clicks on a hyperlink or button and generates action.
- Step 2: - This action is routed to the route provider.
- Step 3: - Router provider scans the URL and loads the view in the place holder defined by “ng-view” attribute.

How can we create a custom directive in Angular?
Till now we have looked in to predefined Angular directives like “ng-controller”,”ng-model” and so on. But what if we want to create our own custom Angular directive and attach it with HTML elements as shown in the below code.
Hide Copy Code
<div id=footercompany-copy-right></div>
To create a custom directive we need to use the “directive” function to register the directive with angular application. When we call the “register” method of “directive” we need to specify the function which will provide the logic for that directive.
For example in the below code we have created a copy right directive and it returns a copy right text.
Please note “app” is an angular application object which has been explained in the previous sections.
Hide Copy Code
app.directive('companyCopyRight', function ()
{
return
{
template: '@CopyRight questpond.com '
};
});
The above custom directive can be later used in elements as shown in below code.
Hide Copy Code
<div ng-controller="CustomerViewModel"> <div company-copy-right></div> </div>
What kind of naming conventions is used for custom directives?
For angular custom directive the best practice is to follow camel casing and that also with atleast two letter’s. In camel case naming convention we start with a small letter, followed by a capital letter for every word.
Some example of camel cases are “loopCounter” , “isValid” and so on.
So when you register a custom directive it should be with camel case format as shown in the below code “companyCopyRight”.
Hide Copy Code
app.directive('companyCopyRight', function ()
{
return
{
template: '@CopyRight questpond.com '
};
});
Later when this directive is consumed inside HTML before each capital letter of camel case we need to insert a “-“ as specified in the below code.
Hide Copy Code
<div company-copy-right></div>

If you are making a one letter prefix like “copyright” it’s very much possible that tomorrow if HTML team creates a tag with the same name, it will clash with your custom directive. That’s why angular team recommends camel case which inserts a “-“ in between to avoid further collision with future HTML tag’s.
What are the different custom directive types in AngularJS?
There are different flavors of Angular directives depending till what level you want to restrict your custom directive.
In other words do you want your custom directive to be applied only on HTML element or only on an attribute or just to CSS etc.
So in all there are four different kinds of custom directives:-
- Element directives (E)
- Attribute directives (A)
- CSS class directives (C)
- Comment directives (M)
Below is a simple custom directive implementation at the element level.
Hide Copy Code
myapp.directive('userinfo', function()
{
var directive = {};
directive.restrict = 'E';
directive.template = "User : {{user.firstName}} {{user.lastName}}";
return directie;
});
The “restrict” property is set to “E” which means that this directive can only be used at element level as shown in the code snippet below.
Hide Copy Code
<userinfo></userinfo>
If you try to use it at an attribute level as shown in the below code it will not work.
Hide Copy Code
<div userinfo></div>
So “E” for element, “A” for attribute, “C” for CSS and “M” for comments.
What if I want custom directives to be applied on element as well as attributes ?
Hide Copy Code
directive.restrict = 'EA';
Can I set an Angular directive template to a HTML web page?
Yes, you can set template to page directly by using “templateUrl” property of the directive as shown in the code snippet below.
Hide Copy Code
directive.templateUrl = "/templates/footer.html";
My other interview question articles
Ques 1. What is AngularJS?
Ans. AngularJS is an open-source JavaScript framework, maintained by Google, that assists with running single-page applications. Its goal is to augment browser-based applications with model–view–controller capability, in an effort to make both development and testing easier.
Is it helpful? Add Comment View Comments
- Android
- Test Results
- Glucose tolerance test results
- Questions and answers
- Online
- Address
- Job interview questions
- Interview Questions
- Angular
- Get Answers
- Android
Ques 2. Can you please explain what is testability like in Angular?
Ans. Very testable and designed this way from ground up. It has an integrated dependency injection framework, provides mocks for many heavy dependencies (server-side communication).
Is it helpful? Add Comment View Comments
Ques 3. Why is this project called "AngularJS"? Why is the namespace called "ng"?
Ans. Because HTML has Angular brackets and "ng" sounds like "Angular".
Is it helpful? Add Comment View Comments
Ques 4. Tell me does Angular use the jQuery library?
Ans. Yes, Angular can use jQuery if it's present in your app when the application is being bootstrapped. If jQuery is not present in your script path, Angular falls back to its own implementation of the subset of jQuery that we call jQLite.
Is it helpful? Add Comment View Comments
Ques 5. Is AngularJS a library, framework, plugin or a browser extension?
Ans.
AngularJS fits the definition of a framework the best, even though it's much more lightweight than a typical framework and that's why many confuse it with a library.
AngularJS is 100% JavaScript, 100% client side and compatible with both desktop and mobile browsers. So it's definitely not a plugin or some other native browser extension
Q1. What is AngularJS?
Ans: AngularJS is open source client side MV* (Model – View – Whatever) framework for creating dynamic web applications. It gives life to your static HTML and makes it dynamic with its magic. It extends HTML using directives, expression and data binding techniques to define a powerful HTML template.
Q2. Is AngularJS a framework, library or a plugin?
Ans: The suitable answer is that its a framework. As its lightweight so people also get confused between library and framework.AngularJS is open source client side MVC framework for creating dynamic web applications.
Q3. Is it same as jQuery?
Ans: NO. jQuery is great library for manipulating the DOM, providing better user experience with animations and effects. You can create website using jQuery but not a web application. jQuery is just a library to play around with HTML, where as AngularJS is a framework to build a dynamic web app as it supports two data binding, MVC, allow testability, templates and many more. Its like AngularJS like a toolbox and jQuery is just a tool. You can read more here.
Q4. Does Angular use the jQuery library?
Ans: YES, Angular can use jQuery if it's present in your app when the application is being bootstrapped. If jQuery is not present in your script path, Angular falls back to its own implementation of the subset of jQuery that we call jQLite.
Q5. Why AngularJS?
Ans: AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.
Q6. What are the key features/concepts of Angular.js?
Ans: When you start learning AngularJS, you will come across following terms and these are the features/concept of AngularJS.
Q7. Is AngularJS is compatible with all modern browsers?
Ans: YES. AngularJS team run extensive test suite against the following browsers: Safari, Chrome, Firefox, Opera 15, IE9 and mobile browsers (Android, Chrome Mobile, iOS Safari).
Q8. What is the basic need to start with AngularJS?
Ans: To start with AngularJS, one need to make reference of angular.js. The latest version of AngularJS can be downloaded from AngularJS.com. You can either download the required js file and then host them locally or you can also use google CDN for referencing it. Here is the link for google CDN url for referencing AngularJS.
Q9. How does the AngularJS framework initialize itself?
Ans: The AngularJS has a self-executing anonymous function present in angular.js code, which does the initialization of AngularJS. Here is how below it looks,
Above function first check if Angular has already been setup. If it has, we return here to prevent Angular from trying to initialize itself a second time. And then it binds jQuery (if present) and publish external API. And finally angularInit() method does the trick for initialization of AngularJS.
Following articles are recommended to know in detail.
How AngularJS Works – Explained with Angular Code
Dissecting Angular: Initializing An App
Q10. What is the bootstrapping in AngularJS?
Ans: Bootstrapping in AngularJS is nothing but just initializing, or starting, your Angular app. AngularJS supports automatic bootstrapping as well as manual way as well. Read moreDifferent ways of bootstrapping AngularJS.
That's all folk for Part-1. Keep visiting for upcoming set of interview questions and answers. You can also subscribe to RSS feed, follow us on Facebook and twitter to get the updates about this blog.
Ans: AngularJS is open source client side MV* (Model – View – Whatever) framework for creating dynamic web applications. It gives life to your static HTML and makes it dynamic with its magic. It extends HTML using directives, expression and data binding techniques to define a powerful HTML template.
Q2. Is AngularJS a framework, library or a plugin?
Ans: The suitable answer is that its a framework. As its lightweight so people also get confused between library and framework.AngularJS is open source client side MVC framework for creating dynamic web applications.
Q3. Is it same as jQuery?
Ans: NO. jQuery is great library for manipulating the DOM, providing better user experience with animations and effects. You can create website using jQuery but not a web application. jQuery is just a library to play around with HTML, where as AngularJS is a framework to build a dynamic web app as it supports two data binding, MVC, allow testability, templates and many more. Its like AngularJS like a toolbox and jQuery is just a tool. You can read more here.
Q4. Does Angular use the jQuery library?
Ans: YES, Angular can use jQuery if it's present in your app when the application is being bootstrapped. If jQuery is not present in your script path, Angular falls back to its own implementation of the subset of jQuery that we call jQLite.
Q5. Why AngularJS?
Ans: AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.
- MVC implementation is done right.
- It extends HTML using directives, expression and data binding techniques to define a powerful HTML template.
- Two way data-binding, form validations, routing supports, inbuilt services.
- REST friendly.
- Dependency injection support.
- It helps you to structure and test your JavaScript code.
Q6. What are the key features/concepts of Angular.js?
Ans: When you start learning AngularJS, you will come across following terms and these are the features/concept of AngularJS.
- Scope
- Directives
- Expression
- Filters
- Data Bindings
- Model
- View
- Controller
- Modules
- Services
- Dependency Injection
Q7. Is AngularJS is compatible with all modern browsers?
Ans: YES. AngularJS team run extensive test suite against the following browsers: Safari, Chrome, Firefox, Opera 15, IE9 and mobile browsers (Android, Chrome Mobile, iOS Safari).
Q8. What is the basic need to start with AngularJS?
Ans: To start with AngularJS, one need to make reference of angular.js. The latest version of AngularJS can be downloaded from AngularJS.com. You can either download the required js file and then host them locally or you can also use google CDN for referencing it. Here is the link for google CDN url for referencing AngularJS.
Q9. How does the AngularJS framework initialize itself?
Ans: The AngularJS has a self-executing anonymous function present in angular.js code, which does the initialization of AngularJS. Here is how below it looks,
01 | (function(window, document, undefined) { |
02 | <!-- |
03 | here goes entire AngularJS code |
04 | including functions, services, providers etc related code goes here |
05 | --> |
06 | if (window.angular.bootstrap) { |
07 | //AngularJS is already loaded, so we can return here... |
08 | console.log('WARNING: Tried to load angular more than once.'); |
09 | return; |
10 | } |
11 | |
12 | //try to bind to jquery now so that one can write angular.element().read() |
13 | //but we will rebind on bootstrap again. |
14 | bindJQuery(); |
15 | |
16 | publishExternalAPI(angular); |
17 | |
18 | jqLite(document).ready(function() { |
19 | angularInit(document, bootstrap); |
20 | }); |
21 | |
22 | })(window, document); |
Following articles are recommended to know in detail.
How AngularJS Works – Explained with Angular Code
Dissecting Angular: Initializing An App
Q10. What is the bootstrapping in AngularJS?
Ans: Bootstrapping in AngularJS is nothing but just initializing, or starting, your Angular app. AngularJS supports automatic bootstrapping as well as manual way as well. Read moreDifferent ways of bootstrapping AngularJS.
That's all folk for Part-1. Keep visiting for upcoming set of interview questions and answers. You can also subscribe to RSS feed, follow us on Facebook and twitter to get the updates about this blog.
Q11. What are templates in AngularJS?
Ans: In Angular, templates are written with HTML that contains Angular-specific elements and attributes. Angular combines the template with information from the model and controller to render the dynamic view that a user sees in the browser. In other words, if your HTML page is having some Angular specific elements/attributes it becomes a template in AngularJS.
Q12. What are directives in AngularJS?
Ans: Directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS to attach a specified behavior to that DOM element or even transform the DOM element and its children. When AngularJS finds the directive at the time of rendering then it attaches the requested behavior to the DOM element. Angular comes with a set of these directives built-in, like ngBind, ngModel, and ngClass.
Q13. Can we create our own directives?
Ans: YES. AngularJS allows us to create our own custom directive.
Q14. What are different type or classification of directives?
Ans: AngularJS directives can be classified in 4 different types .
Q15. What is the name of directive is used to bootstrap an angular app?
Ans: ng-app directive is used to auto-bootstrap an AngularJS application. The ng-appdirective defines the root element of the application and is typically present in the root element of the page - e.g. on the <body> or <html> tags.
Q16. Can AngularJS have multiple ng-app directives in a single page?
Ans: The answer is NO. Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. If you have placed another ng-app directive then it will not be processed by AngularJS. You need to manually bootstrap the second app, instead of using second ng-app directive. Read How to define multiple angular apps on the same page?
Q17. Can angular applications (ng-app) be nested within each other?
Ans: NO. AngularJS applications cannot be nested within each other.
Q18. Can you bootstrap multiple angular applications on same element?
Ans: NO. If you try to do that then it will show an error "App Already Bootstrapped with this Element". This usually happens when you accidentally use both ng-app andangular.bootstrap to bootstrap an application. You can also get this error if you accidentally load AngularJS itself more than once.
Q19. In how many different ways, you can define a directive and what is the best practice?
Ans: Angular generally prefers camelCase for directives. But since HTML is not case-sensitive so it refers to directive in DOM in lower case form, delimited by dash (eg. ng-app). But when Angular complies then it normalize the directives.
Below are example of valid directive declaration.
The normalization process is as follows:
1. Strip x- and data- from the front of the element/attributes.
2. Convert the :, -, or _-delimited name to camelCase.
The best practice to use dash-delimited (ng-model) or directly camelCase form (ngModel). If you are using HTML validation tool, then it is advised to use data- prefixed version. And it also answers another question which is "Difference between ng-* and data-ng-*".
Q20. Mention some angularJS directives and their purpose?
Ans: The beauty of AngularJS directives is that they are self explainatory. By just looking at directive name, you will get the idea about purpose and use of directive. Below are some mostly used directives.
ng-app : Initializes application.
ng-model : Binds HTML controls to application data.
ng-Controller : Attaches a controller class to view.
ng-repeat : Bind repeated data HTML elements. Its like a for loop.
ng-if : Bind HTML elements with condition.
ng-show : Used to show the HTML elements.
ng-hide : Used to hide the HTML elements.
ng-class : Used to assign CSS class.
ng-src : Used to pass the URL image etc.
Event Listeners
ng-click : Click event to bind on HTML elements.
ng-dbl-click
Mouse event listeners
ng-mousedown
ng-mouseup
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
Keyboard event listeners
ng-keydown
ng-keyup
ng-keypress
ng-change
It's a long list. You can find about all the directives here.
Ans: In Angular, templates are written with HTML that contains Angular-specific elements and attributes. Angular combines the template with information from the model and controller to render the dynamic view that a user sees in the browser. In other words, if your HTML page is having some Angular specific elements/attributes it becomes a template in AngularJS.
Q12. What are directives in AngularJS?
Ans: Directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS to attach a specified behavior to that DOM element or even transform the DOM element and its children. When AngularJS finds the directive at the time of rendering then it attaches the requested behavior to the DOM element. Angular comes with a set of these directives built-in, like ngBind, ngModel, and ngClass.
Q13. Can we create our own directives?
Ans: YES. AngularJS allows us to create our own custom directive.
Q14. What are different type or classification of directives?
Ans: AngularJS directives can be classified in 4 different types .
- Element directives
1<ng-directive></ng-directive> - Attribute directives
1<span ng-directive></span> - CSS class directives
1<span class="ng-directive: expression;"></span> - Comment directives
1<!-- directive: ng-directive expression -->
Q15. What is the name of directive is used to bootstrap an angular app?
Ans: ng-app directive is used to auto-bootstrap an AngularJS application. The ng-appdirective defines the root element of the application and is typically present in the root element of the page - e.g. on the <body> or <html> tags.
Q16. Can AngularJS have multiple ng-app directives in a single page?
Ans: The answer is NO. Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. If you have placed another ng-app directive then it will not be processed by AngularJS. You need to manually bootstrap the second app, instead of using second ng-app directive. Read How to define multiple angular apps on the same page?
Q17. Can angular applications (ng-app) be nested within each other?
Ans: NO. AngularJS applications cannot be nested within each other.
Q18. Can you bootstrap multiple angular applications on same element?
Ans: NO. If you try to do that then it will show an error "App Already Bootstrapped with this Element". This usually happens when you accidentally use both ng-app andangular.bootstrap to bootstrap an application. You can also get this error if you accidentally load AngularJS itself more than once.
Q19. In how many different ways, you can define a directive and what is the best practice?
Ans: Angular generally prefers camelCase for directives. But since HTML is not case-sensitive so it refers to directive in DOM in lower case form, delimited by dash (eg. ng-app). But when Angular complies then it normalize the directives.
Below are example of valid directive declaration.
- ng-model
- ngModel
- ng:model
- ng_model
- data-ng-model
- x-ng-model
The normalization process is as follows:
1. Strip x- and data- from the front of the element/attributes.
2. Convert the :, -, or _-delimited name to camelCase.
The best practice to use dash-delimited (ng-model) or directly camelCase form (ngModel). If you are using HTML validation tool, then it is advised to use data- prefixed version. And it also answers another question which is "Difference between ng-* and data-ng-*".
Q20. Mention some angularJS directives and their purpose?
Ans: The beauty of AngularJS directives is that they are self explainatory. By just looking at directive name, you will get the idea about purpose and use of directive. Below are some mostly used directives.
ng-app : Initializes application.
ng-model : Binds HTML controls to application data.
ng-Controller : Attaches a controller class to view.
ng-repeat : Bind repeated data HTML elements. Its like a for loop.
ng-if : Bind HTML elements with condition.
ng-show : Used to show the HTML elements.
ng-hide : Used to hide the HTML elements.
ng-class : Used to assign CSS class.
ng-src : Used to pass the URL image etc.
Event Listeners
ng-click : Click event to bind on HTML elements.
ng-dbl-click
Mouse event listeners
ng-mousedown
ng-mouseup
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
Keyboard event listeners
ng-keydown
ng-keyup
ng-keypress
ng-change
It's a long list. You can find about all the directives here.
Q21. What is Angular Expression?
Ans: Angular expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. For example, these are valid expressions in Angular:
Q22. How Angular expressions are different from JavaScript expressions?
Ans: Angular expressions are like JavaScript expressions but there are few differences.
Q23. What is compilation process in Angular?
Ans: Once you have the markup, the AngularJS needs to attach the functionality. This process is called "compilation" in Angular. Compiling includes rendering of markup, replacing directives, attaching events to directives and creating a scope. The AngularJS has compiler service which traverses the DOM looking for attributes. The compilation process happens in two phases.
To understand the compilation process of Angular, must read "The nitty-gritty of compile and link functions inside AngularJS directives".
Q24. What is scope in AngularJS?
Ans: A scope is an object that ties a view (a DOM element) to the controller. In the MVC framework, scope object is your model. In other words, it is just a JavaScript object, which is used for communication between controller and view.
Q25. What is $rootscope in AngularJS?
Ans: The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope. Since $rootScope is a global, which means that anything you add here, automatically becomes available in $scope in all controller. To add something in $rootScope, you need to use app.run function which ensures that it will run prior to the rest of the app. You may say that "run" function is like "main" method of angular app.
And then you can use in your view. (via expression)
Q26. What are controllers in AngularJS?
Ans: In Angular, a Controller is a JavaScript constructor function. When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. The job of a controller is to pass data from the model, to the view or the view can asks for something from the controller, and the controller turns to the model and takes that thing, and hands it back to the view.
And then in your HTML using ng-controller directive,
Q27. What is the difference between $scope and scope in AngularJS?
Ans: $scope is used while defining a controller (see previous question) where scope is used while creating a link function for custom directive. The common part is that they both refers to scope object in AngularJS, but the difference is that $scope uses dependency injection where scope doesn't. When the arguments are passed-in via dependency injection, their position doesn't matter. So for example, a controller defined as ($scope as first parameter)
OR ($scope is second parameter)
In both the case, the postion of $scope doesn't matter to AngularJS. Because AngularJS uses the argument name to get something out of the dependency-injection container and later use it.
But in case of link function, the position of scope does matter because it doesn't uses DI. The very first parameter has to be scope and that's what AngularJS expects.
However you can name it anything of your choice. In below code, foo is your scope object.
Q28. What is MVC Architecture in AngularJS?
Ans: In AngularJS, scope objects are treated as Model. The View is display of model that is your data. And the model gets initialized within a JavaScript constructor function, calledController in AngularJS. Let take a look at below code to understand it better.
Here MyController is a Controller and $scope (Model) is populated within Controller. And later on in div element $scope object data is displayed (View).
Q29. Can we have nested controllers in AngularJS?
Ans: YES. We can create nested controllers in AngularJS. Nested controller are defined in hierarchical manner while using in View. Take a look at below code. Here the hierarchy is "MainCtrl -> SubCtrl -> SubCtrl1".
Q30. In case of nested controllers, does the $scope object shared across all controllers?
Ans: YES. The $scope object is shared across all controllers and it happens due to scope inheritance. Since the ng-controller directive creates a new child scope, we get a hierarchy of scopes that inherit from each other. So if we define a property on a parent scope, the child scope can manipulate the property. And if the property is not present in child scope, then parent scope property's value is used. Lets consider, the previous question HTML where there are 3 controllers. And here is the AngularJS code to define these controllers.
You will see that the controller "SubCtrl2" doesn't have "message" property define but it is used in HTML. So in this case, the immediate parent scope property will be used. But immediate parent scope which is "SubCtrl" in this case, also doesn't have "message" property. So it again goes one level up and finds the property is present so it uses parent scope value for "message" property and displays it
Ans: Angular expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. For example, these are valid expressions in Angular:
- {{ 3+4 }}
- {{ a+b }}
- {{ user.name }}
- {{ items[index] }}
Q22. How Angular expressions are different from JavaScript expressions?
Ans: Angular expressions are like JavaScript expressions but there are few differences.
- Context : In Angular, the expressions are evaluated against a scope object, while the JavaScript expressions are evaluated against the global window object.
- 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.
- No Comma And Void Operators: You cannot use , (comma) or void in an Angular expression. And You cannot create regular expressions in an Angular expression.
Q23. What is compilation process in Angular?
Ans: Once you have the markup, the AngularJS needs to attach the functionality. This process is called "compilation" in Angular. Compiling includes rendering of markup, replacing directives, attaching events to directives and creating a scope. The AngularJS has compiler service which traverses the DOM looking for attributes. The compilation process happens in two phases.
- Compilation : traverse the DOM and collect all of the directives and creation of the linking function.
- Linking: combine the directives with a scope and produce a live view. The linking function allows for the attaching of events and handling of scope. Any changes in the scope model are reflected in the view, and any user interactions with the view are reflected in the scope model.
To understand the compilation process of Angular, must read "The nitty-gritty of compile and link functions inside AngularJS directives".
Q24. What is scope in AngularJS?
Ans: A scope is an object that ties a view (a DOM element) to the controller. In the MVC framework, scope object is your model. In other words, it is just a JavaScript object, which is used for communication between controller and view.
Q25. What is $rootscope in AngularJS?
Ans: The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope. Since $rootScope is a global, which means that anything you add here, automatically becomes available in $scope in all controller. To add something in $rootScope, you need to use app.run function which ensures that it will run prior to the rest of the app. You may say that "run" function is like "main" method of angular app.
1 | app.run(function($rootScope) { |
2 | $rootScope.name = "AngularJS"; |
3 | }); |
1 | <body ng-app="myApp"> |
2 | <h1>Hello {{ name }}!</h1> |
3 | </body> |
Q26. What are controllers in AngularJS?
Ans: In Angular, a Controller is a JavaScript constructor function. When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. The job of a controller is to pass data from the model, to the view or the view can asks for something from the controller, and the controller turns to the model and takes that thing, and hands it back to the view.
1 | var myApp = angular.module('myApp', []); |
2 | myApp.controller('MyController', ['$scope', function($scope) { |
3 | $scope.website = 'jquerybyexample.net'; |
4 | } |
5 | ]); |
1 | <div ng-controller="MyController"> |
2 | <h1>My website address is {{ website }}!</h1> |
3 | </div> |
Q27. What is the difference between $scope and scope in AngularJS?
Ans: $scope is used while defining a controller (see previous question) where scope is used while creating a link function for custom directive. The common part is that they both refers to scope object in AngularJS, but the difference is that $scope uses dependency injection where scope doesn't. When the arguments are passed-in via dependency injection, their position doesn't matter. So for example, a controller defined as ($scope as first parameter)
1 | myApp.controller('MyController', ['$scope', function($scope, $http) { |
1 | myApp.controller('MyController', ['$scope', function($http, $scope) { |
But in case of link function, the position of scope does matter because it doesn't uses DI. The very first parameter has to be scope and that's what AngularJS expects.
1 | app.directive("myDirective", function() { |
2 | return { |
3 | scope: {}; |
4 | link: function(scope, element, attrs) { |
5 | // code goes here. |
6 | } |
7 | }; |
8 | }); |
1 | link: function(foo, bar, baz) { |
2 | // code goes here. |
3 | } |
Q28. What is MVC Architecture in AngularJS?
Ans: In AngularJS, scope objects are treated as Model. The View is display of model that is your data. And the model gets initialized within a JavaScript constructor function, calledController in AngularJS. Let take a look at below code to understand it better.
01 | <!DOCTYPE html> |
02 | <html> |
03 |
04 | <head> |
05 | <script data-require="angular.js@*" data-semver="1.3.6"src="https://code.angularjs.org/1.3.6/angular.js"></script> |
06 | <link rel="stylesheet" href="style.css" /> |
07 | <script> |
08 | var myApp = angular.module('myApp', []); |
09 | myApp.controller('MyController', ['$scope', |
10 | function($scope) { |
11 | $scope.website = 'jquerybyexample.net'; |
12 | } |
13 | ]); |
14 | </script> |
15 | </head> |
16 |
17 | <body ng-app="myApp"> |
18 | <div ng-controller="MyController"> |
19 | <h1>My website address is {{ website }}</h1>; |
20 | </div> |
21 | </body> |
22 | </html> |
Q29. Can we have nested controllers in AngularJS?
Ans: YES. We can create nested controllers in AngularJS. Nested controller are defined in hierarchical manner while using in View. Take a look at below code. Here the hierarchy is "MainCtrl -> SubCtrl -> SubCtrl1".
01 | <div ng-controller="MainCtrl"> |
02 | <p>{{message}} {{name}}!</p> |
03 |
04 | <div ng-controller="SubCtrl"> |
05 | <p>Hello {{name}}!</p> |
06 |
07 | <div ng-controller="SubCtrl2"> |
08 | <p>{{message}} {{name}}! Your username is {{username}}.</p> |
09 | </div> |
10 | </div> |
11 | </div> |
Q30. In case of nested controllers, does the $scope object shared across all controllers?
Ans: YES. The $scope object is shared across all controllers and it happens due to scope inheritance. Since the ng-controller directive creates a new child scope, we get a hierarchy of scopes that inherit from each other. So if we define a property on a parent scope, the child scope can manipulate the property. And if the property is not present in child scope, then parent scope property's value is used. Lets consider, the previous question HTML where there are 3 controllers. And here is the AngularJS code to define these controllers.
01 | var myApp = angular.module('myApp', []); |
02 | myApp.controller('MainCtrl', ['$scope', |
03 | function($scope) { |
04 | $scope.message = 'Welcome'; |
05 | $scope.name = 'Jon'; |
06 | } |
07 | ]); |
08 | myApp.controller('SubCtrl', ['$scope', |
09 | function($scope) { |
10 | $scope.name = 'Adams'; |
11 | } |
12 | ]); |
13 | myApp.controller('SubCtrl2', ['$scope', |
14 | function($scope) { |
15 | $scope.name = 'Ema'; |
16 | $scope.username = 'ema123'; |
17 | } |
18 | ]); |

