Showing posts with label Interview Question Answer. Show all posts
Showing posts with label Interview Question Answer. Show all posts

Thursday, September 27, 2018

Angularjs Interview Questions and Answers


1.What is AngularJS?

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.

2.What are the uses of AngularJS?

Below are the uses of AngularJS –
It uses MVC pattern.
Allows to create our own directive for making components reusable.
Used for two way binding i.e, connecting model and view.
Supports Dependency Injection (DI)

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

4.List out the advantages of AngularJS?

Below is the list of advantages of AngularJS –
Code Reusability
Data Binding
Testing
Support
Customize and Extensible

5.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 is 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 boilerplate like validating the form, displaying validation errors, returning to an internal model and so on which occurs due to flow of marshaling 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.

6.Is AngularJS extensible?

Yes! In AngularJS we can create a custom directive to extend AngularJS existing functionalities.
Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using “directive” function. A custom directive simply replaces the element for which it is activated. AngularJS application during bootstrap finds the matching elements and do one-time activity using its compile() method of the custom directive then process the element using link() method of the custom directive based on the scope of the directive.

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

8.How AngularJS is used to handle the security hurdles?

Below is the list of security hurdles handled by AngularJS –
Used for preventing CSS attacks
Used for preventing XSRF protection
Used for preventing HTML injection

9.Who created Angular JS ?

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

10.Is AngularJS a framework, library or a plugin?

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.

11. Is it same as jQuery?

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.

12. Does Angular use the jQuery library?

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.

13. Why AngularJS?

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.

14. What are the key features/concepts of Angular.js?

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

15. List out the components which can be used in AngularJS modules?

Below are the list of components –
Controller
Filter
Provider
Factory
Routes
Service
Directive

16. Is AngularJS is compatible with all modern browsers?

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

17. What Are The Security Features Provided By AngularJS?

AngularJS provides built-in protection from the following security flaws.
It prevents cross-side 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: It can be handled by “Auth token” mechanism. 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.

18. What is MVC Architecture in AngularJS?

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, called Controller in AngularJS. Let take a look at below code to understand it better.

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

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

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

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.

21.What is the basic need to start with AngularJS?

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.

22. What is the bootstrapping in AngularJS?

Bootstrapping in AngularJS is nothing but just initializing, or starting, your Angular app. AngularJS supports automatic bootstrapping as well as manual way as well.

23. How AngularJS will automatically be initialized?

AngularJS will be initialized during “DOMContentLoaded” event or during the angular.js file download to browser. Now AngularJS looks for directive – “ng-app”, which is a root compilation for AngularJS.

24. Explain module in AngularJS?

Modules are like namespaces in C#. Modules are used for dividing single page angular app to functional, reusable and small components and can be integrated with another angular app. Module can be assigned using “ng-app” directive.

25. Explain how we can create module and using it in AngularJS?

Below is the code snippet for creating and using module in AngularJS –
Creating a module –
<script type=”text/javascript”>
angular.module(‘myFirstApp’, []);
angular.module(‘myFirstApp’, [‘MydependentModule1’, ‘MydependentModule2’]);
</script>
Using the Module –
<html ng-app=”‘myFirstApp’”>
<head> … </head>
<body> … </body>
</html>

26. Which is the core module of AngularJS?

“ng” is the core module of AngularJS and when angular app is started this module will be loaded by default.

27.What are different ways of bootstrapping AngularJS?

Is neat and superheroic JavaScript MVW (Model View Whatever) Framework which allows to extend HTML capabilities with Directives, expression, two way binding. In this post, we will see different ways of bootstrapping AngularJS. Bootstrapping in AngularJS is nothing but just the initialization of Angular app.
There are two ways of bootstrapping AngularJS. One is Automatic Initialization and other is Manually using Script.
When you add ng-app directive to the root of your application, typically on the tag or tag if you want angular to auto-bootstrap your application.
<html ng-app=”myApp”>
When angularJS finds ng-app directive, it loads the module associated with it and then compiles the DOM.
Another way to bootstrapping is manually initializing using script. Manual initialization provides you more control on how and when to initialize angular App. It is useful when you want to perform any other operation before Angular wakes up and compile the page. Below is the script which allows to manually bootstrap angularJS.
<script>angular.element(document).ready(function() {angular.bootstrap(document, [‘myApp’]);});</script>
If you have noticed, it is using document.ready which is great as it will make sure that before bootstrapping your DOM is ready. You don’t need to include jQuery library reference here, as angularJS has within it. So angular.bootstrap function bootstrap angularJS to document. The second parameter is the name of module. You need to take care of following things while using manual process.
Remember angular.bootstrap function will not create modules on the go. So you need to have your modules define, before you manually bootstrap. So below is the correct approach. First define the module and then bootstrap

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

29. What are controllers in AngularJS?

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. Rather, for manipulating the DOM, we should use data binding and directives.
Do not use Controllers to format input. Rather, 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.
Following code displays the definition of SampleController.
<script>
function SampleController($scope) {
$scope.sample = {firstSample: “INITIAL”,  lastSample: “Initial”,  fullName: function() {
var sampleObject;
sampleObject = $scope.sample;
return sampleObject.firstSample + ” ” + sampleObject.lastSample;
}
};
}</script>

30. Can we have nested controllers in AngularJS?

YES. We can create nested controllers in AngularJS. Nested controller is defined in a hierarchical manner while using in View.

31. In case of nested controllers, does the $scope object shared across all controllers?

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.

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

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 a view is found, it is linked 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.

33. What Is An Auto Bootstrap Process In AngularJS?

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.
1.Create the application injector.
2.Compile the DOM starting from the ng-app root element.
3.This process is auto-bootstrapping.
Following is the sample code that helps to understand it more clearly:
<html>
<body ng-app=”myApp”>
<div ng-controller=”Ctrl”>Hello {{msg}}!</div>
<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js”></script>     <script>
var app = angular.module(‘myApp’, []);
app.controller(‘Ctrl’, function($scope) {
$scope.msg = ‘Welcome’;
});
</script>
</body>
</html>

34.What Is The Manual Bootstrap Process In AngularJS?

Sometimes we may need to manually initialize Angular app in order 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.
Following is the sample code that helps to understand the concept more clearly.
<html>
<body>
<div ng-controller=”Ctrl”>Hello {{msg}}!</div>
<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js”></script>        <script>
var app = angular.module(‘myApp’, []);
app.controller(‘Ctrl’, function($scope) {
$scope.msg = ‘Welcome’;
});
//manual bootstrap process
angular.element(document).ready(function () { angular.bootstrap(document, [‘myApp’]); });
</script>
</body>
</html>

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

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 for the newly created module. Other modules act as dependent modules for this newly created module.
Let’s take an example, suppose we have two modules: module1 and model2. To initialize the app automatically, based on these two modules following code is used
<html>
<head>
<title>
Multiple modules bootstrap
</title>
<script src=”lib/angular.js”></script>
<script>
//module1
var app1 = angular.module(“module1”, []); app1.controller(“Controller1”, function ($scope) { $scope.name = “Welcome”; });

//module2
var app2 = angular.module(“module2”, []); app2.controller(“Controller2”, function ($scope) { $scope.name = “World”; });

//module3 dependent on module1 & module2
angular.module(“app”, [“module1”, “module2″]);
</script>
</head>
<body>
<!–angularjs autobootstap process–>
<div ng-app=”app”>
<h1>Multiple modules bootstrap</h1>
<div ng-controller=”Controller2″>
</div>
<div ng-controller=”Controller1″>
</div>
</div>
</body>
</html>

36. Can AngularJS have multiple ng-app directives in a single page?

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.

37. Can angular applications (ng-app) be nested within each other?

AngularJS applications cannot be nested within each other.

38. Can you bootstrap multiple angular applications on same element?

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 and angular.bootstrap to bootstrap an application. You can also get this error if you accidentally load AngularJS itself more than once.

39. What are templates in AngularJS?

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.

40. What is scope in AngularJS?

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.

41.What is $rootscope in AngularJS?

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

42.What is the difference between Rootscope and Scope in AngularJS?

Rootscope – Rootscope is the top most scope and one application can have an only one rootscope and will be shared among all the components.
Scope – Scope will act as a glue between view and controller and scopes are arranged in the hierarchical structure.

43.Give an example for Rootscope in AngularJS?

Rootscope acts as a global variable and below is the sample code for the same –
<html>
<body ng-app=”mytestApp”>
<div ng-controller=”MyFirstController” style=”border:2px solid blue; padding:5px”>
Hi {{mymsg}}!
<br />
Hi {{myname}}! (rootScope)
</div>
<br />
<div ng-controller=”MySecondController” style=”border:2px solid green; padding:5px”>
Hello {{mymsg}}!
<br />
Hi {{name}}! (rootScope)
</div>
<script src=”/lib/angular.js”></script>
<script>
var app = angular.module(‘mytestApp’, []);
app.controller(‘MyFirstController’, function ($scope, $rootScope) {
$scope.msg = ‘Good Morning’;
$rootScope.name = ‘Test My scope’;
});
app.controller(‘MySecondController’, function ($scope, $rootScope) {
$scope.msg = ‘Good Night’;
$scope.CheckName = $rootScope.name;
});
</script>
</body>
</html>

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

45.What are expressions in AngularJS?

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)

46.Explain One-way binding in AngularJS?

This type of binding is being introduced in angularJS version – 1.3 and double colon – “::” is used for one-time expression. Below is the example of using it –
Eg : {{:: mytestname }}

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

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

48.Give an example of Data binding in AngularJS?

<div ng-app=”” ng-init=”quantity=10;cost=5″ class=”ng-scope”>
<b>Total Cost: {{cost * quantity}}</b>
</div>

49.What are directives in AngularJS?

Directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS to attach a specified behaviour 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 behaviour to the DOM element. Angular comes with a set of these directives built-in, like ngBind, ngModel, and ngClass.

50.Explain directive in AngularJS?

Directive are the combination of javascript code and AngularJS markup. Javascript directive code defines the behaviours and template data of HTML elements. There are some built-in directives like – “ng-controller”,”ng-app”, “ng-repeat” etc.

51. 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 behaviour 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.

52. Explain what is data binding in Angular.js ?

Whenever a web page loads in the browser, following steps execute in the background.
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

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

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)<ng-bind> – 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 ng-bind=”expression”> </ANY ELEMENT>
2)<ng-bind-html>– 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 ng-bind-html=” expression “> </ANY ELEMENT>
3)<ng-bind-template>– 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 ng-bind-template=” {{expression1}} {{expression2}} … {{expressionn}} “> </ANY ELEMENT>
4)<ng-non-bindable>– 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 ng-non-bindable > </ANY ELEMENT>
5)<ng-model>– 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 behaviour. It also retains the state of the control (like valid/invalid, touched/untouched and so on).
It has the following Syntax.
<input ng-bind=”expression”/>

54.Explain The Directives Ng-If, Ng-Switch, And Ng-Repeat?

A) <Ng-If>.
This directive can add/remove HTML elements from the DOM based on an expression. If the expression is true, it adds a copy of HTML elements to the DOM. If the expression evaluates to false, this directive removes the HTML element from the DOM.
<div ng-controller=”MyCtrl”>
<div ng-if=”data.isVisible”>ng-if  Visible</div>
</div><script>
var app = angular.module(“app”, []);
app.controller(“MyCtrl”, function ($scope) {
$scope.data = {};
$scope.data.isVisible = true;
});
</script>
B)<Ng-Switch>.This directive can add/remove HTML elements from the DOM conditionally based on scope expression.
Child elements with the directive will be displayed if it gets a match, else the element and its children get removed. It also allows defining a default section, by using the directive. It displays a section if none of the other sections match.
Let’s see the following example that displays the syntax for .
<div ng-controller=”MyCtrl”>
<div ng-switch on=”data.case”>
<div ng-switch-when=”1″>Shown when case is 1</div>
<div ng-switch-when=”2″>Shown when case is 2</div>
<div ng-switch-default>Shown when case is anything else than 1 and 2</div>         </div></div><script>
var app = angular.module(“app”, []);
app.controller(“MyCtrl”, function ($scope) {
$scope.data = {};
$scope.data.case = true;
});
</script>
C) <Ng-Repeat>.
This directive is used to iterate over a collection of items and generate HTML from it.
<div ng-controller=”MyCtrl”>
<ul>
<li ng-repeat=”name in names”>
{{ name }}
</li>
</ul></div>
<script>
var app = angular.module(“app”, []);
app.controller(“MyCtrl”, function ($scope) {
$scope.names = [ ‘Mahesh’, ‘Raj’, ‘Diksha’ ];
});
</script>

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

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.

56. What is ngClass directive in AngularJS?

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>

57. How to load select box during page initialization using AngularJS?

Below is the sample code to initialize the select box using AngularJS –
<div ng-controller = “mycontroller” ng-init = “loaddataforselectBox()”>
</div>

58. How looping has been done in AngularJS?

Looping can be achieved like below in AngularJS –
<ul>
<li data-ng-repeat=”mytestname in names”>
{{ mytestname }}
</li>
</ul>

59. How to display the values in tables in AngularJS?

Below is the sample code for showing the data in table –
<table>
<tr>
<th>Product Name</th>
<th>Product Type</th>
</tr>
<tr ng-repeat=”product in category.products”>
<td>{{ product.name }}</td>
<td>{{ product.type }}</td>
</tr>
</table>

60. Can we create our own directives?

YES. AngularJS allows us to create our own custom directive.

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

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.

62.What are different type or classification of directives?

AngularJS directives can be classified in 4 different types:-
Element directives:
<ng-directive></ng-directive>
Attribute directives:
<span ng-directive></span>
CSS class directives:
<span class=”ng-directive: expression;”></span>
Comment directives:
<!– directive: ng-directive expression –>

63.How to define multiple restrict options on a directive in AngularJS?

We can specify multiple restrict options for supporting more than one method. All methods should specify restrict keyword like below –    restrict: ‘TA’

64.What is the name of directive is used to bootstrap an angular app?

ng-app directive is used to auto-bootstrap an AngularJS application. The ng-app directive 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.

65.In how many different ways, you can define a directive and what is the best practice?

Angular generally prefers camelCase for directives. But since HTML is not case-sensitive so it refers to directive in DOM in lowercase 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

66.Mention some angularJS directives and their purpose?

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

67.What are the ways to track the error in AngularJS?

Below are the ways to track the error in AngularJS –
$error – This will state the exact error.
$dirty – This will indicate if the value is being changed.
$invalid – This will indicate in case the value entered is wrong or invalid.

68.Explain filters in AngularJS?

Filters are mainly used to format the data before displaying it in the screen to the user. This can be used in services, controllers, directives and templates.
Eg: Syntax of the filter
{{ expression | filter}}
<script type=”text/javascript”>
{ { 25 | currency } } //returns $25.00
</script>

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

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:
<p> {{ bid | currency }} </p>
The above example is an expression enclosed in the curly braces. The filter used in this expression is currency. Also important to note that filters are case-sensitive.
AngularJS provides following filters to transform data.
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 a 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.

70.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 contain embedded expressions. As part of normal digest cycle these expressions are updated and registered as watches.

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

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

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

74.Explain what is Dependency Injection in AngularJS?

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.

75.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)   {   });

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

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.

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

78.When To Use Factory?

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.

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

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

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, that makes the Angular codes, robust and less error prone.
  1. 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 very simple 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 – This service is useful to write, read and delete browser cookies.
$parse – This service is useful to convert AngularJS expression into a function.
$cacheFactory – This service evaluates the specified expression when the user changes the input.

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

There are 5 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.
  1. AngularJS Factory.
Value service may be very easy to write but, it lacks many important 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 in 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.
  1. 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 <num> 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.
  1. 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”);}]);
  1. 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 at 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’);

82.List out the differences between config and run methods in AngularJS?

Config Block – Constants and providers can be injected into config blocks and this block can be created using config method.
Run Block – Run block will be executed after config block. Run block is used to inject constants and instances and this block can be created using run method.
Eg :
angular.module(‘myTestModule’, []).
config(function (injectables) {
// config block
}).
run(function (injectables) {
// run block
});

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

Using a service 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();
});

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

85.What are animating elements in AngularJS?

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

86.Explain RouteProvider in AngularJS?

$routeProvider is the key service which set the configuration of URLs, map them with 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 <addEmployee.htm> should be present in the same path as main HTML page.
“otherwise” is used to set the default view.
“controller” is used to set the corresponding controller for the view.

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

88.Explain how routing works in AngularJS?

Routing enables to create different URL for different content in our application. Different content for different URL enables to bookmark the URL of specific content and this is called route and this mechanism is called routing.

89.What Is Ng-View In AngularJS?

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.

90.How to make Http get request from AngularJS with an example?

From AngularJS we can use “$http” service. Below is the sample code for http get request –
$http.get(‘/MyURL’).
success(function(data, status, headers, config) {
// code here
}).
error(function(data, status, headers, config) {
// code here
});

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 in the browser. Let’s learn about each of the three phases 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 survives until the user reloads or navigates away from the webpage. 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.

92.Why to use “$http” in AngularJS?

“$http” is used as an AngularJS service to read data from remote server.
“$http.get(url)” method is used for this purpose by specifying the url as a parameter.

93.What are the methods available in $http ?

$http.get This method is used to get data from requested url
$http.post This method is used to send data to request url
$http.put This method is used to send data to specified url
$http.delete This method is used to delete resource from specified url

94.What are the Output of AngularJS $http Service?

In angularjs once $http service operation finished then we will receive response object. The response object is having different properties those are
config – The configuration object is used to generate the request.
data – It’s string or an object which is used to carry response from the server.
headers – This function is used to get header information.
status – This property is used to get HTTP status code of the response.
statusText – This property is used to get HTTP status text of the response

95.What is $log Service?

AngularJs includes logging service $log, which logs the messages to the browser’s console.The $log service includes different methods to log the error, information, warning or debug information. It can be useful in debugging and auditing.
<!DOCTYPE html>
<html>
<head>
<script src=”~/Scripts/angular.js”>
</script>
</head>
<body ng-app=”myApp” >
<div ng-controller=”myController”>
<p>Please check the browser console for the logging information.</p>
</div>
<script>
var myApp = angular.module(‘myApp’, []);
myApp.controller(“myController”, function ($log) {
$log.log(‘This is log.’);
$log.error(‘This is error.’);
$log.info(‘This is info.’);
$log.warn(‘This is warning.’);
$log.debug(‘This is debugging.’);
});
</script>
</body>
</html>
Please check the browser console for the logging information.

96.What is $interval service in AngularJS?

AngularJS includes $interval service which performs the same task as setInterval() method in JavaScript. The $interval is a wrapper for setInterval() method, so that it will be easy to override, remove or mocked for testing.
The $interval service executes the specified function on every specified milliseconds duration.
Syntax: $interval(fn, delay, [count]);

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

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.

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

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.

99.Explain AngularJS Application Life-Cycle?

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 in the browser. Let’s learn about each of the three phases 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.

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

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, that 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 very simple 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.
$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.
$filter – Used for providing filter access.
$document – Used to access the window. Document object.
$cacheFactory – This service evaluates the specified expression when the user changes the input.

JavaScript Related Questions & Answers

1.What is JavaScript? JavaScript is a client-side as well as server side scripting language that can be inserted into HTML pages an...