New 42 AngularJS Advanced Interview Questions And Answers Pdf

1. Can’t retrieve the injector from angularjs ?

Answer:

Before answering the question we need to note that there is only one injector instance per application and not per module. In this sense it is not possible to retrieve an injector per module. Of course if we take the top-level module it represents the whole application so in this sense an application and top-level module seem equivalent. It might seem like a subtle difference but it is important to understand in order to fully and properly answer this question.
Next, from what I can understand you would like to retrieve the $injector and not create a new instance of it. The thing is that the angular.injector will create a new $injector instance for modules (an app) specified as arguments. Here the main AngularJS module (ng) must be specified explicitly. So, in this code example:
var injector = angular.injector([‘gaad’, ‘components’]);
you were trying to create a new injector from components defined in ‘gaad’ and ‘components’ modules and obviously $compileProvider is not defined in your custom modules. Adding the ngmodule to the list would “solve” the problem by creating a new injector – something that you probably don’t want to happen.
To actually retrieve an injector instance associated to a running application we can use 2 methods:

from within AngularJS JavaScript the simplest solution is just to inject$injector instance:https://docs.angularjs.org/api/angular.injector
from outside of AngularJS world – callelement([DOM element]).injector() where [DOM element] is a dome element where the ng-app was defined (or any child element of this element). More info here: https://docs.angularjs.org/api/angular.element
Here is the jsFiddle showing 2 methods
Please also note that using $injector directly is not very common scenario outside of unit testing. It might be useful thought for retrieving AngularJS services from outside of AngularJS world.

AngularJS Advanced Interview Questions And Answers Pdf

2. What are the new features of Angular2 ?

Answer:

Component-Based- Angular 2 is entirely component based. Controllers and $scope are no longer used. They have been replaced by components and directives.
Directives- The specification for directives is considerably simplified, although they are still subject to change. With the @Directive annotation, a directive can be declared.
Dependency Injection- Because of the improved dependency injection model in Angular2 there are more opportunities for component / object-based work.
Use of TypeScript-TypeScript is a typed super set of JavaScript which has been built and maintained by Microsoft and chosen by the AngularJS team for development. The presence of types makes the code written in TypeScript less prone to run-time errors. In recent times, the support for ES6 has been greatly improved and a few features from ES7 have been added as well.
Generics- TypeScript has generics which can be used in the frontend.
Lambdas with TypeScript- In TypeScript, lambdas are available.
Forms and Validations- Forms and validations are an important aspect of frontend development. Within Angular 2 the Form Builder and Control Group are defined.

3. How do we share data between controllers ?

Answer:
1. Create an AngularJS service that will hold the data and inject it inside the required controllers.

2. Services help to create reusable components

3. A typical service can be injected into another service or into an AngularJS Controller.

4. Using a service is the cleanest, fastest and easiest way to test.

4. What is the difference between ng-show/ng-hide and ng-if directives ?

Answer:
ng-show/ng-hide will just show or hide the DOM element based on the given condition.

ng-if will insert or remove the DOM element based on the given condition.

ng-show will show or hide the DOM element based on the given condition.

ng-if is better when we needed the DOM to be loaded conditionally, as it will help load page bit faster compared to ng-show/ng-hide.

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

Answer:
An AngularJS Filter changes or transforms the data before passing it to the view. These Filters work in combination with AngularJS expressions or directives. AngularJS uses pipe character (“|”) to add filters to the expressions or directives. For example:

{{ bid | currency }}

The above example is an expression enclosed in the curly braces. The filter used in this expression is currency. Also important to note that filters are case-sensitive.

AngularJS provides following filters to transform data.

currency – It is used to format a number to a currency format.
date – It is required to format a date to a specified format.
filter – It chooses a subset of items from an array.
json – It formats an object to a JSON string.
limitTo – Its purpose is to create an array or string containing a specified number of elements/characters. The elements are selected, either from the beginning or the end of the source array or string. This depends on the value and sign (positive or negative) of the limit.
lowercase – This filter converts a string to lower case.
number – It formats a number as text.
orderBy – It enables to sort an array. By default, sorting of strings happens alphabetically. And sorting of numbers is done numerically. It also supports a comparator function where we can define what will be counted as a match or not.
uppercase – This filter converts a string to upper case.

Top 47 AngularJS Interview Questions And Answers For Experienced

6. What Are Angular Prefixes $ And $$ ?

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

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

7. Distinguish between AngularJS expression & JavaScript expression ?

Answer:
AngularJS expression:

1. Expressions are evaluated against $scope.

2. Expression evaluation is forgiving to null and undefined.

3. In AngularJS, loops, conditions and exceptions are not required to write.

4. AngularJS supports filters to format data before displaying.

JavaScript Expression:

1. Expressions are evaluated against Window object.

2. Undefined properties generates Type Error or Reference Error

3. In AngularJS, loops, conditions and exceptions are required to write.

4. No such a feature.

8. Explain route configuration? And explain with code ?

Answer:
1. We have to download angular-route.js script or need to use CDN in application.

2. Inject ngRoute in application module.

3. Config() takes a function which takes $routeProvider as parameter and routing configuration goes inside the function.

4. When() method takes URL, templateUrl and controller.

A. URL property takes part of URL after # link.

B. templateUrl property takes html template AngularJS load.

C. Controller property defines which controller should be used with html template.

AngularJS Advanced Interview Questions And Answers Pdf

9. What is $scope? How it works ?

Answer:
1. $Scope is an object and it refers to application model.

2. $scope is glue between controller and view.

3. During the template linking phase, directives set up $watch expressions on scope.

4. $watch allows directives to be notified whenever properties get changed, this will get reflected in DOM.

10. Explain service? When we should use service ?

Answer:

1. Service is singleton object and it gets instantiated only once per application.

2. Service are gets initialized when angular application components need them.

3. Services can be used in any controller to communicate data across the application.

4. Services should be used when we need to share common functionality in application.

5. Some in-built services are $https, $scope, $provide, $resource, $window and $parse etc.

11. What are Globals in Node.js ?

Answer:

Three keywords in Node.js constitute as Globals. These are:

Process – It is one of the global objects but can turn a synchronous function into an async callback. It can be accessed from anywhere in the code and it primarily gives back information about the application or the environment.
Buffer – it is a class in Node.js to handle binary data.

12. What is the difference between AngularJS and Node.js ?

Answer:

Angular.JS is a web application development framework while Node.js is a runtime system.

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

Answer:

Following are the most critical web application development flaws that a developer should take care of:

Injection attack.
Broken Authentication and Session Management.
Cross-Site Scripting (XSS)
Insecure direct object references.
Security Misconfiguration.
Sensitive Data Exposure.
Missing Function Level Access Control.
Cross-Site Request Forgery (CSRF).
Using components that possess vulnerabilities.
In-validated redirects and forwards.

14. What Is Ng-View In AngularJS ?

Answer:

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.

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

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

Answer:

A) Compile – It collects an HTML string or DOM into a template and produces a template function. It can then be used to link the scope and the template together.

AngularJS uses the compile function to change the original DOM before creating its instance and before the creation of scope.

Before discussing the Pre-Link and the Post-Link functions let’s see the Link function in detail.

B) Link – It has the duty of linking the model to the available templates. AngularJS does the data binding to the compiled templates using Link.

Scope – It is the scope of the directive.
element – It is the DOM element where the directive has to be applied.
attr- It is the Collection of attributes of the DOM element.
ctrl – It is the array of controllers required by the directive.
AngularJS allows setting the link property to an object also. The advantage of having an object is that we can split the link function into two separate methods called, pre-link and post-link.

C) Post-Link – Execution of Post-Link function starts after the linking of child elements. It is safer to do DOM transformation during its execution. The post-link function is suitable to execute the logic.

D) Pre-Link – It gets executed before the child elements are linked. It is not safe to do DOM transformation. As the compiler linking function will fail to locate the correct elements.

It is good to use the pre-link function to implement the logic that runs when AngularJS has already compiled the child elements. Also, before any of the child element’s post-link functions have been called.

16. AngularJS Value ?

Answer:

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.

AngularJS Advanced Interview Questions And Answers Pdf

17. AngularJS Service ?

Answer:

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

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

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

app.factory(“MyExampleService”,[“num” ,function(num){
return new MyExample(num);
}]);
Thus in this way, we will create its new instance and return it. Also, we have injected as a dependency in Factory service. Now, let’s see how we can do this using Service type:

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

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

Answer:

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

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

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

scope.name = ‘shailendra’;
scope.counter = 0;
scope.$watch(‘name’, function (newVal, oldVal) {
scope.counter = scope.counter + 1; });
B) $Watchgroup.
This function was introduced in Angular 1.3. It works in the same way as $watch() function except that the first parameter is an array of expressions.

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

$scope.teamScore = 0;
$scope.time = 0;
$scope.$watchGroup([‘teamScore’, ‘time’], function(newVal, oldVal) {
if(newVal[0] > 20){
$scope.matchStatus = ‘win’;
}
else if (newVal[1] > 60){
$scope.matchStatus = ‘times up’;
});
C) $WatchCollection.
This use of this function is to watch the properties of an object. It gets fired when there is any change in the properties. It takes an object as the first parameter and watches the properties of the object.

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

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

19. Explain validations done in AngularJS ?

Answer:

AngularJS will leverage on HTML 5 validations. Below is the sample code for required field validation.

20. How we can check for errors for specific field in AngularJS ?

Answer:

Using “$valid” property we can check the validity of the form inside “ng-app” directive.

21. Explain Two-way binding in AngularJS ?

Answer:

“ng-model” is being used for two-way model binding. Whenever any change in the model, view will be updated automatically and vice versa.

22. What is internationalization and how to implement it in AngularJS ?

Answer:

Internationalization is a way in which you can show locale specific information on a website. AngularJS supports inbuilt internationalization for three types of filters: currency, date and numbers. To implement internalization, we only need to incorporate corresponding js according to locale of the country. By default it handles the locale of the browser.

23. On which types of component can we create a custom directive ?

Answer:

AngularJS provides support to create custom directives for the following:

Element directives − Directive activates when a matching element is encountered.
Attribute − Directive activates when a matching attribute is encountered.
CSS − Directive activates when a matching css style is encountered.
Comment − Directive activates when a matching comment is encountered.

24. What is $rootscope in AngularJS ?

Answer:

Every application has a single root scope. All other scopes are descendant scopes of the root scope. Scopes provide separation between the model and the view, via a mechanism for watching the model for changes. They also provide event emission/broadcast and subscription facility.

AngularJS Advanced Interview Questions And Answers Pdf

25. Explain One-way binding in AngularJS ?

Answer:

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 –

26. What Would You Do To Limit A Scope Variable To Have One-Time Binding ?

Answer:

By prefixing the “::” operator to the scope variable. It’ll make sure the candidate is aware of the available variable bindings in AngularJS.

27. What is the difference between Angular 1(Angularjs) and Angular ?

Answer:

Angular 2/4 is complete revamp of Angular 1.In fact, we can say that it was completely rewritten from the ground-up.

28. What is the difference between AngularJS 1(Angularjs) and Angular 2/4 ?

Answer:

Angular 2/4 is complete revamp of Angular 1.In fact, we can say that it was completely rewritten from the ground-up.

Angular 1 is controller and $scope based while Angular 2/4 is based on an architecture of component hierarchy, dependency injections and directives.

Angular 2/4 is much more geared towards Mobile development unlike Angular 1 as mobile development is much bug prone. If mobile development is handled first desktop development will not have much issues.

Angular 2/4 focuses much more on modularity as much of its core functionality has been transferred to its modules leading to a faster and lighter application in development.

Angular 2/4 is mainly written in Typescript Which introduces features like Class-based Object Oriented Programming, Generics and Static Typing to framework, which makes it more appealing to developers from non-JavaScript background and leading to shorter development time.

Unlike Angular 1, Angular 2/4 is mainly introduced to be compatible with modern browsers. Angular 2/4 not only introduces new features like lazy loading/Dynamic loading, Asynchronous template compilation, Simpler Routing and Reactive programming support-using RxJS but also improves on legacy features like dependency injection.

29. What is Typescript ?

Answer:

➔ In Simple word Typescript is a Superset of JavaScript meaning any JavaScript code is valid typescript code.
Typescript is Trans piled to JavaScript behind the scene in the IDE.
JavaScript is function based which can get confusing to a C# or Java developer while reviewing code So Typescript allows us to use generic programming (classes and modules).
Typescript follows the ECMAScript 2015 standard which contains features like:
➢Generic
➢Namespaces
➢Enumerated type
➢Interfaces etc.

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

Answer:

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.

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

Answer:

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.

32. What are expressions in AngularJS ?

Answer:

Expressions in AnjularJS are used to bind application data to html. They are written inside double braces like {{expression}} and behaves in same way as ng-bind directives. They are pure JavaScript expressions and outputs the data where they are used. E.g.

AngularJS Advanced Interview Questions And Answers Pdf

33. Explain $scope in Angular ?

Answer:

‘$scope’ is an object instance of a controller. ‘$scope’ object instance gets created when ‘ng-controller’ directive is encountered. E.g.

function Function1($scope)

$scope.ControllerName = “Function1”;

function Function2($scope)

$scope.ControllerName = “Function2”;

34. What should be the maximum number of concurrent “watches” ?

Answer:

There should be a maximum of 2000 to reduce memory consumption and improve performance.

35. What is a digest cycle in AngularJS ?

Answer:

A digest cycle is the code that runs at an interval. This interval may be sometimes simply as fast as possible after the previous one, and sometimes the interval is set.

36. How can you decrease digest cycle time ?

Answer:

Digest cycle time can be decreased by decreasing the number of watchers.

37. What is currency filter? What are the two ways to use currency filters ?

Answer:

The “currency” filter includes the “$” Dollar Symbol as the default. here are two ways by which we can use Currency Filter:

default, where the Dollar-sign will be used in default. E.g. {{amount | currency}}
user-defined, where the user defines the currency. E.g. Indian Currency {{amount | currency:”&# 8377″}}

AngularJS Advanced Interview Questions And Answers Pdf

38. What is directive and what are the different types of Directives ?

Answer:

A behaviour or function is triggered during compilation process when specific HTML constructs are encountered, this function is called as the 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

39. What is linking function and what are the types of linking function ?

Answer:

Link combines the directives with a scope and produces a live view. Link function is responsible for registering DOM listeners as well as updating the DOM. It is executed after the template is cloned.

Pre-linking function:Pre-linking function is executed before the child elements are linked. For DOM transformation,It is not considered as the safe way.
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.

40. Angular.js: Is .value() the proper way to set app wide constant and how to retrieve it in a controller ?

Answer:

Module.value(key, value) is used to inject an editable value, Module.constant(key, value)is used to inject a constant value
The difference between the two isn’t so much that you “can’t edit a constant”, it’s more that you can’t intercept a constant with $provide and inject something else.
Skip code block
// define a value
app.value(‘myThing’, ‘weee’);
// define a constant
app.constant(‘myConst’, ‘blah’);
// use it in a service
app.factory(‘myService’, [‘myThing’, ‘myConst’, function(myThing, myConst){
return {
whatsMyThing: function() {
return myThing; //weee
},
getMyConst: function () {
return myConst; //blah

// use it in a controller
app.controller(‘someController’, [‘$scope’, ‘myThing’, ‘myConst’,
function($scope, myThing, myConst) {
$scope.foo = myThing; //weee
$scope.bar = myConst; //blah

41. how to debug the $rootScope object of angularjs when in the browser ?

Answer:

+1 for Batarang
Also, you can get the scope from any element in the DOM by executing the following from the console
angular.element(DOMNODE).scope()
Where DOMNODE, is of course, a reference to a DOM node.
For example, in Chrome in the elements tab you can select the node where the ng-app directive is, and get the root scope with
angular.element($0).scope()

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

Answer:

Angular expressions are code snippets that are usually placed in the binding as in Javascript. {{expression}}

The key difference between the JavaScript expressions and Angular expressions

Context: Angular, the evaluation of expressions are done against a scope object, while in the Javascript, the evaluation of expressions is done against the global window

Forgiving: In Angular expression, evaluation is done by forgiving to null and undefined, whereas in Javascript undefined properties generates TypeError or ReferenceError

No Control Flow Statements: in an angular expression Loops, conditionals or exceptions cannot be used..