Explore topic-wise InterviewSolutions in Current Affairs.

This section includes 7 InterviewSolutions, each offering curated multiple-choice questions to sharpen your Current Affairs knowledge and support exam preparation. Choose a topic below to get started.

1.

What is the difference between the $ and the $$ prefixes?

Answer»

The $$ PREFIX is used to define a private variable in AngularJS. This is responsible for avoiding accidental code changes due to exposure to the variables. Examples are $$observers, $$watchers, $$childScope etc.
The $ prefix is used for defining built-in core AngularJS FUNCTIONALITIES like variable, parameter, method, or any properties. Examples are $scope, $http, $routeProvider, $watch etc.

Conclusion:
In this ARTICLE, we have seen the most commonly asked AngularJS interview questions for both the freshers and. the experienced developers. AngularJS was initially created to establish the concept of dependency injection and ease the development of single-page APPLICATIONS. Despite AngularJS being the first version, many companies have adopted this framework due to its raging benefits, easy configuration, and extensibility. Even though the framework has undergone a lot of changes in its different versions and releases, AngularJS has been the most useful framework for developing web applications in different companies.

References: 

https://angularjs.org/
https://thinkster.io/a-better-way-to-learn-angularjs

Recommended Resources:

Javascript Interview
ANGULAR Interview
Angular 8 Interview
Difference Between Angular and AngularJS
Angular Vs React

2.

What are the lifecycle hooks available?

Answer»

There are many lifecycle hooks available in AngularJS and they are:

  • NGONINIT(): This is a CALLBACK method that gets invoked as soon as the change detector detects any scope model changes for the first time and before any view has been checked. This is invoked once only when the directive is instantiated.
  • ngOnChanges(): This callback function is triggered whenever AngularJS detects changes in the scope model and we can define the actions that need to follow up with that change in the PROPERTY. It is called before ngOnInit() while instantiating the directive and is called every time the scope model changes.
  • ngDoCheck(): This callback method does the task of change-detection and is invoked only after the default change-detector is run.
  • ngAfterContentInit(): This is invoked once and that too as soon as AngularJS completes the initialization of all content of the DIRECTIVES.
  • ngAfterContentChecked(): This callback method is invoked as soon as the default change-detector completes checking the content of the directives.
  • ngOnDestroy(): This is USED to clean up any component just before the directives or its properties are destroyed. They are useful for avoiding memory leaks and unsubscribe any unnecessary observables.
  • ngAfterViewChecked(): This is immediately invoked once the default change-detector completes one cycle of change-check.
3.

What is the auto bootstrap process?

Answer»

Auto Bootstrapping is the process of automatically initiating the DOMContentLoaded EVENT in the BROWSER. The AngularJS application after downloading the angular.js library into the browser does the task of finding the ng-app directive which gives the root of the application. Once the directive is found, the following steps take place:

  • The angular root MODULE associated with the ng-app directive is loaded.
  • The application injector is created which in turn creates the $compile and the $rootScope objects.
  • The DOM is compiled from the ng-app element automatically and the CONTENT is rendered on the browser. This process is CALLED auto bootstrapping.
4.

How do you achieve internationalization?

Answer»

Internationalization is a way of showing locale-specific CONTENT on our applications. For example, the website in the UNITED Kingdom needs to be displayed in English whereas the same website needs to be shown in HINDI for the users of India. By incorporating multiple languages support in our platform, we are ensuring that our website reaches a wider target audience.

Internationalization is supported in AngularJS using the angular-translate module which has lots of filters and directives and also the ABILITY to asynchronously load i18n based data. The module also provides support for pluralization by MAKING use of the highly configurable MessageFormat.

5.

How can you maintain logs in AngularJS?

Answer»

Logs in AngularJS can be maintained by using the $log built-in service. These are mainly used for TROUBLESHOOTING and debugging in case of any unexpected scenarios. They are done by mainly using the below methods:

  1. log(): To log a message onto the console. Example usage: $log.log(‘Entered some function’)
  2. INFO(): To write any message which represents information. Example usage: $log.info(‘Data PROCESSED successfully’)
  3. warn(): To log warnings. Example usage: $log.warn(‘The value is empty.’)
  4. error(): To log errors. Example usage: $log.error(‘OH no! Something WENT wrong.’)
  5. debug(): To log any debug messages useful for debugging. Example usage: $log.debug(‘Processed a variable A.’)
6.

How will you hide an HTML tag element on click of a button click in AngularJS? Write a program for the same.

Answer»

This can be achieved by making use of the ng-click DIRECTIVE that controls the condition USED for manipulating the display of the tag in the ng-hide directive.

<!DOCTYPE HTML><html><head> <meta chrset="UTF 8"> <title>Button Click Hide</title></head><body> <script src="https://code.angularjs.org/1.6.9/angular.js"></script> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <div ng-app="buttonDemo" ng-controller="buttonDemoController"> <button ng-click="hideTag()">Hide IntervieBit</button> <div ng-hide="hideFlag">InterviewBit</div> </div> <script type="text/javascript"> var app = angular.module('buttonDemo',[]); app.controller('buttonDemoController',function($SCOPE){ $scope.hideFlag = false; $scope.hideTag = function(){ $scope.hideFlag = true; } }); </script></body></html>
7.

What is the difference between the scopes of a directive and the scopes of a controller?

Answer»

Scopes of the controller and the directives are the instances of scope objects. The only difference lies in the naming convention for them. To understand the difference between scope and $scope, we NEED to understand directives with isolated scope using the following code:

app.directive('testAppDirective', function() { return { scope: {}, link: function(myScopeVariable, elem,attr) { console.log(scope); } }});

Here, we have defined a directive with isolated scope. The link function takes the signature scope, element, and attribute as the parameters. The name of the signature scope parameter can be anything as that parameter will be tagged to the scope of the directive’s object. The $scope object that is USUALLY injected into the controller cannot be used with another name. For example,

app.controller(‘myTestController’,function(newScope){});

results in error Error: 

[$injector:unpr] Unknown provider: scopeProvider <- scope <- myTestController

Because the AngularJS dependency SYSTEM tries to locate the dependency of the name newScope but fails to FIND it. Hence, to mark the dependency appropriately, the input to the controller function should be $scope.

8.

How will you improve performance of an AngularJS application?

Answer»

AngularJS makers have recommended the below two approaches for performance OPTIMIZATION in the production environment. They are:

  • Enable strict DI mode: This can be achieved by making use of the directive ngStrictDi and can be implemented as:
<html ng-app=“myFirstApp” ng-strict-di>
  • Disable debug data: This can be achieved by using the debugInfoEnabled method of the $compileProvider service as shown below:
app.config(function ($compileProvider) { $compileProvider.debugInfoEnabled(false);});

Apart from the above two, we can also improve the performance by following the below tips:

  • Implementing one-time binding whenever possible.
  • By making $httpProvider use the applyAsync feature. - - By refraining from creating many $watchers UNNECESSARILY as too many of the watchers will lengthen the digest cycle thereby reducing the speed.
  • If you have scenarios like repeated data calculations of the same nature, then we can make use of the $cacheFactory directive to store the data to avoid recalculations.
  • In case we have a large number of elements to be looped, then instead of LOADING everything at once, pagination or infinite SCROLL can be implemented to reduce the data load. AngularJS PROVIDES ngInfiniteScroll directive for accomplishing the infinite scroll feature.

For more information regarding the tools that can be used to measure AngularJS performance, you can read here.

9.

What are the different phases of the lifecycle of AngularJS Scope?

Answer»

The following diagram illustrates the scope lifecycle in AngularJS:

  • Creation: In this phase, the rootScope is created by $injector during the application bootstrap. During the phase of template linking, new child scopes relevant to the directives are created.
  • Watcher registration: Here, the directives register the watches on the scope object which will be used to propagate values of models to DOM.
  • Model MUTATION: The model mutations need to be PRESENT within the scope.$apply() for them to be properly observed. These will be done implicitly by AngularJS when WORKING on synchronous or asynchronous work requests.
  • Mutation observation: Once the $apply is complete, the digest CYCLE STARTS to observe for any model mutations on the scopes. Here, the $watches expressions are monitored for the model mutations and if any mutations are observed, then the $watch listener is called on the model.
  • Scope destruction: As and when the child scopes are unnecessary, the creator of the scopes would have to destroy them by making use of scope.$destroy(). This ensures that the $digest cycle propagations are stopped and the memory once used by the child scopes is reclaimed.
10.

What can you say about the digest phase in AngularJS?

Answer»

The digest cycle or digest phase is the most important cycle required for the data binding process. It does the TASK of comparing the OLD version of a model with its new version. Whenever a CHANGE in the scope model is found during the comparison, the model watches are fired and another digest phase is initiated until the scope model is stable.

The digest cycle can be triggered manually by MAKING use of $apply() or can be triggered automatically. The digest cycle gets triggered automatically when we use the core directives of AngularJS. In case we have any EXTERNAL code changes, then that would require manual triggering of the digest cycle.

The following diagram illustrates the process of the digest cycle clearly.

11.

What are AngularJS filters?

Answer»

AngularJS FILTERS are mainly used for formatting an expression while displaying it to the user. These can be used in controllers or services or views. AngularJS provides several inbuilt filters such as currency, FILTER, DATE, JSON, limitTo, etc whose purpose is to format the data without actually changing its VALUE before merging to the expression and this is done by using the pipe character (|). AngularJS also provides support for registering and implementing custom filters and use them using the pipe symbol.

Syntax for using filters:

{{expression | filterName:filterInputParameter }}

For example, to format data to display the currency symbol before the salary value of say 18000:

{{salary | currency:'Rs.'}}

The salary will be displayed as “Rs.18,000”. Here ‘Rs.’ is the input to currency filter to define formatting. If nothing is specified, the default is considered as Dollars ($).

You can look into the implementation of different TYPES of filters in the official documentation of AngularJS here.

12.

Is it possible to create nested controllers?

Answer»

YES, it is possible to create nested controllers in AngularJS.
The SAMPLE code SNIPPET can be as shown below:

&LT;div ng-controller="mainController"> <p>{{message}} {{name}}!</p> <div ng-controller="childController1"> <p>Welcome to our app, {{name}}!</p> <div ng-controller="subChildController2"> <p>{{message}} {{name}}! You are our esteemed GUEST {{name}}.</p> </div> </div></div>
13.

Why do we use ng-include?

Answer»

The ng-include DIRECTIVE is used for helping us to embed HTML PAGES inside a single HTML page. For example:

&LT;div ng-app = "" ng-controller = "interviewBitController"> <div ng-include = "'sample.htm'"></div> <div ng-include = "'example.htm'"></div></div>

In the above snippet, we are trying to include/embed sample.htm and example.htm page into our current ANGULARJS page.

14.

What is the importance of orderBy?

Answer»

orderBy is a built-in filter in ANGULARJS that HELPS to re-order the array items based on defined CRITERIA. For example, if we need to sort the items based on the ascending order of price, then we can follow the below code:

<UL><li ng-repeat = "item in items | orderBy:'price"> {{ item.name + ', price:' + item.price }}</li></ul>
15.

What is the importance of the $location service?

Answer»

$location is one of the built-in AngularJS services that HELPS to keep track of the application’s URL, parses it, and makes the value available to the controller. In case the $location value is changed in the controller, the same is reflected on the browser’s ADDRESS BAR. Changes to the URL on the address bar also result in reflection of the same on the $location service.

16.

Write a syntax to send sample HTTP POST request in AngualrJS?

Answer»

To PERFORM any AJAX calls, AngularJS makes USE of the $http service. The syntax is as below:

$http({ METHOD: "POST", url: "URL", data: JSON.stringify(VALUE), contentType: 'application/json' }).then(function (successResponse) { // success callback action of the request },function (errorResponse) { // error callback action of the request });
17.

How does routing work in AngularJS?

Answer»

Routing enables us to create different URLs according to different contents in our app which in turn enables the users of the application to bookmark the contents as per their requirements. The route is that URL that can be bookmarked. Routing also helps in developing SPA (Single Page Applications) i.e create a single HTML page and update that page dynamically as and when the user interacts.

AngularJS supports routing by making use of its routing module called “ngRoute”. This module acts according to the URL. Whenever a user requests for a specific route/URL, the routing engine of the module, also called $routeProvider, renders the view based on that URL and defines what controller acts on this view - all based on the routing rules defined.

Consider the below snippet:

var myApp = angular.module('routingExample', ['ngRoute']);myApp.config(function ($routeProvider) { $routeProvider.when('/', { templateUrl: '/login-page.html', controller: 'loginPageController' }).when('/employee/:empName', { templateUrl: '/employee-page.html', controller: 'employeeController' }).otherwise({ redirectTo: "/" });})

In the above example, we can see that to implement routing, we need to follow the below steps:

  • While creating the application module, pass ‘ngRoute’ as the dependency module like below:
var myApp = angular.module('routingExample', ['ngRoute']);
  • Next, configure the routing rules for the application module by making use of the config() method by taking the $routeProvider service as the dependency.
  • The $routeProvider.when(path, route) method is used for configuring the rules of routing where the first parameter defines what is the request URL and the second parameter defines the object CONTAINING the template, controller, and other PROPERTY details that need to function upon requesting the URL.
    • In the given example, if the user requests for “/login-page.html”, then INJECT login-page.html into the view and use the loginPageController.
    • For the URL “/employee/:empName” URL, the :empName refers to the URL parameter dynamically populated in the URL.
    • The otherwise() method is used for redirecting to the default or base URL for any other requests that are not part of the rules CONFIGURED.
18.

Differentiate between compile and link in AngularJS?

Answer»

Compile is like a service used for TRAVERSING the HTML to find all the DIRECTIVES and return link functions.
The link does the task of combining the model with a view where any changes made to the model are REFLECTED in the view and VICE versa.
More information on compile and link can be found here.

19.

What does the following code do? What are the permitted values of the restrict attribute?

Answer»

app.directive('myFirstDirective', function() { return { restrict: 'E', SCOPE: { directiveInfo: '=directiveInfo' }, templateUrl: 'my-first-directive.html' };});

  • In the given piece of CODE, we have defined a custom directive called “myFirstDirective”. Based on the value of restrict, we can say that the directive is RESTRICTED only to the element names. The directive has an isolated scope which has a property called “directiveInfo” that will be getting its value from the “directiveInfo” attribute of the element directive. The view or the template URL used for making the directive work is “my-first-directive.html”.
  • Following are the possible values of the restrict attribute in AngularJS directives:
    • ‘A’ - attribute names are MATCHED.
    • ‘E’ - element names are matched.
    • ‘C’ - class names are matched.
    • ‘M’ - only comments are matched.
20.

What is the importance of track by in the ng-repeat directive?

Answer»

ng-repeat DIRECTIVE helps to keep track of all DOM elements dynamically to minimize DOM creation and rendering. It is achieved by storing the instances of the object whenever a new element gets added to the LIST or collection. AngularJS just renders the newly added element instead of re-rendering the overall collection. This helps in rendering the elements faster.

In case the ng-repeat is operated on a collection that has the objects of unique identifier, the tracking of new elements should be done based on that ID instead of new instance insertion. This can be done by making use of the track by provided by the ng-repeat. For example, in the below piece of code:

<DIV ng-repeat="obj in objectList track by obj.id"> <!--Some code --></div>

the tracking of new elements is done using the object’s id.

21.

What can you tell about the given piece of code?

Answer»

<SELECT ng-options="employee.name for employee in employeeList"&GT;</select>

The given piece of code would throw syntax error because in AngularJS it is not possible to use ng-options directives without USING the ng-model directive. The ng-options dynamically generate the <option> ELEMENTS for the given <select> element by evaluating the expression within it. Now upon selecting the element from the dropdown, the option value needs to be bound to a model which is DEFINED by the ng-model directive. Absence of the ng-model results in error.

22.

Is it possible for a parent controller to access the methods and properties of the child controller?

Answer»

No, the PARENT CONTROLLER can’t access the PROPERTIES and the methods of the CHILD controller. But the child controller can access the parent’s methods.

23.

Why is the findIndex() method used? What does it return in case the value is not found?

Answer»

findIndex() METHOD returns the position of the element in any object. In case the element is not found then the method returns -1.
For example:

var index = $scope.objectsList.findIndex(OBJ =&GT; obj.DATE =='2021-21-06');

Here, the index of the object where it has the date property value EQUAL to 2021-21-06 is returned.

24.

How can you reset a $timeout and disable a $watch()?

Answer»

In order to reset $TIMEOUT, we call the .CANCEL() method on it. as shown below:

var myTimer = $timeout(FUNCTION() { /* your code */ }, 1000);$timeout.cancel(myTimer);

To disable $watch, we can just call it as shown below:

var deregisterWatch = $scope.$watch(function() { /* Your code */ });deregisterWatch(); // CALLING the WATCHER disables it.
25.

How is the mouse double click event accomplished?

Answer»

To specify any custom behaviour upon double click EVENT on any HTML element, AngularJS MAKES use of the ng-dblclick directive. It is to be NOTED that the ng-dblclick does not override the JavaScript’s ondblclick event. Example usage of this directive:

<BUTTON ng-dblclick="clicked = clicked + 1" ng-init="clicked=0"&GT; Double Click Here</button>

The above piece of code increments the clicked variable by 1 upon every double click on the button.

26.

List out the scope characteristics in AngularJS?

Answer»

Scope object has 5 IMPORTANT characteristics.

  • It provides the application with a context against which the AngularJS expressions are evaluated.
  • It provides an option to observe the model CHANGES WITHIN them using the $WATCH watcher service.
  • The scope objects provide APIs like $apply that help in propagating the model changes throughout the application into the view from the sources like controllers, services, or VARIOUS AngularJS event handlers.
  • Scope objects inherit the parent properties and provide access to shared model properties.
  • Scopes can even be nested to isolate directives and various AngularJS components.
27.

Differentiate between expressions of AngularJS and JavaScript.

Answer»

AngularJS expressions are placed INSIDE double curly BRACES {{expression}} similar to JavaScript. The main DIFFERENCES between them are:

AngularJS expressionsJavaScript expressions
The expressions are EVALUATED against the scope object that they are part of.The expressions are evaluated against the global window scope.
Expression evaluation nature is forgiving. If something goes wrong, it returns null or undefined.JavaScript expressions are not forgiving in nature and return an error.
Here, loops and conditional statements cannot be ADDED as part of expressions. Loops and conditional statements can be part of JavaScript expressions.
Previous Next