Important AngularJs Questions

Aditya kumar
Last Updated: May 13, 2022

1. What is AngularJS, and what are its main characteristics?

Google's AngularJS is a popular open-source JavaScript-based framework for building large-scale, enterprise-level, dynamic, single-page web applications. AngularJS's primary template language is HTML, and its syntax is used to express the application's components, such as directives. By integrating the capabilities of JavaScript and the MVC architecture, AngularJS is used primarily to construct client-side functionality. This combination of capabilities enables the creation of enterprise-level online programs that are easy to maintain and cross-browser compatible.

The following are the main characteristics of AngularJS:

  • Applications - AngularJS applications are thoroughly tested.
  • Data binding - The most significant element of AngularJS is data binding, which allows data to be synchronised between the model and view components in the framework.
  • Controllers - Controllers are JavaScript functions bound to scope in AngularJS, and they are referred to as controllers.
  • Services - Services AngularJS comes with several built-in services, including $http, which aids with XMLHttpRequests and AJAX requests.
  • Scope - A scope is a specific object provided by AngularJS that refers to models and acts as a glue between the view and the controller.
  • Filters - AngularJS comes with several built-in filters and can create custom filters to help subset array objects and filter depending on specific criteria.
  • Directives - Directives are the markers for DOM elements like attributes, features, CSS, etc. They're utilised to make custom HTML tags that can be used as widgets. AngularJS has built-in directives like ngBind, ngModel, ngHide, and others and can create user-defined directives for code reuse.
  • Routing - The most significant feature supported by AngularJS is routing, which involves switching views depending on any circumstance.
  • MVC Pattern - AngularJS follows the MVC pattern, which stands for Model-View-Controller design and helps it allocate responsibilities effectively. Model is in charge of the application's data management. Views are responsible for displaying application data, whereas controllers serve as a link between the Model and the View to apply application logic.
  • Dependency Injection - AngularJS was built primarily to illustrate dependency injection. By defining interactions and resolving dependencies between distinct components, this feature makes it easier for developers to design, maintain, and test applications.

 

2. In AngularJS, define Scope.

Scopes are AngularJS objects that connect the view and the controller. They refer to the model component of the MVC architecture. They're arranged in a hierarchical order to match the DOM structural hierarchy. The $scope object in AngularJS holds all of the application's data and associated methods.

 

Source: Scope in AngularJs

 

3. What do the services in AngularJS stand for?

Services are discrete objects that accomplish the tasks for which they were created. The Dependency Injection principle, which supports the framework in structuring and sharing code across the application, connects them. By default, AngularJS contains a large number of services. AngularJS also supports custom services, which are more commonly used by developers.

                                                                   Source: Services in AngularJs

 

4. What do you mean by directives?

Directives are the most significant AngularJS elements since they are DOM element markers that give new functionality to DOM components such as names, attributes, CSS classes, and comments. They are used to create custom HTML tags that function similarly to custom widgets. The directives ng-model for data binding, ng-repeat for iterating components, ng-app for bootstrapping AngularJS apps, and ng-show, ng-hide for changing the visibility of DOM elements are all included in AngularJS.

For Example:

<div ng-app="" ng-init="firstName='John'">

<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>

</div>

 

5. Describe the AngularJS data binding process.

Data binding is a method of syncing data between the display and model components automatically. The built-in directives ng-model and ng-bind are used by AngularJS to accomplish this. This directive ensures that the model is the view's only source of truth and that the view is always in sync with it. Data can be bound using one of two methods:

One-Way Data Binding: Changes in the model are reflected in the view, but changes in the view to the data are not. The binding connects the model and the view in just one direction. This is accomplished via the ng-bind directive.

Source: One Way Data Binding

 

Two-Way Data Binding: Changes in the model are reflected in the view, and changes in the view are reflected in the model, as the name implies. The ng-model directive is used to accomplish this.

Source: Two Way Data Binding 

 

6. In AngularJS, what is the purpose of interpolation?

The process of linking data together by embedding phrases in attribute and text nodes is known as interpolation. The compiler's job is to match the text and characteristics during the compilation process. Internally, AngularJS uses the $interpolate built-in service to look for embedded expressions in markup, and if any are found, they are updated and registered as watches.

Source: Interpolation in AngularJs

 

7. What is an AngularJS Module?

An AngularJS module is a container for keeping track of various components of an AngularJS application, including controllers, filters, directives, services, and so on, and as well as a place to construct dependencies between them. It's similar to the primary considered() function in Java. The module() method of the angular object can be used to construct an AngularJS module.

You're defining an app module for the myFirstApp application, for example, in the code below. You can define all of this module's dependencies, if any, within the square brackets.

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

 

As illustrated in the figure, we may define all of the controllers, filters, constants, and directives in the app module:

Source: Modules

 

To define a controller, for example, we use the following method:

app.controller("FirstController", ['$scope', function(obj) {
   obj.item = "Item 1";
}
]);

 

8. In an AngularJS application, define $rootScope.

$rootScope refers to the scope object produced on the DOM element containing the ng-app directive for bootstrapping the AngularJS application. This object is present throughout the entire AngularJS application. There can only be one $rootScope object in the entire application. All other scope objects are the child scopes of that $rootScope object.

 

9. Recognize the differences between the ng-if and ng-show directives.

The DOM element section is not rendered if the ng-if directive's condition is not met. The element's scope will be destroyed if this is not rendered.

On the other hand, the ng-show directive renders the DOM element but hides the display if the condition it specifies isn't met (by applying the ng-hide class to that DOM element).

 

10. What is the purpose of $watch?

The $watch variable keeps track of the previous and new values of the expression or model variable that is being watched. Consider the following as an example:

 

$scope.$watch("trackedVariable", 
   function (newValue, oldValue){
       console.log("Value Changed : ", newValue);
   });

 

We're keeping an eye on the model variable trackedVariable in the example above. If its value changes, we print it on the console right away.

 

11. How do you disable a $watch() and reset a $timeout?

$timeout is reset by calling the cancel() method on it. as shown below:

 

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

 

We can just call $watch as indicated below to disable it:

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

 

12. Explain MVC in terms of AngularJS.

In AngularJs, the model for a controller holds data, the controller for a view holds the logic for manipulating that data, and the view is the HTML that displays the data.

 

With angular controller functions altering the $scope and HTML showing the scope variable's value, a $scope can be thought of as a model.

 

Source: MVC

 

13.  What are custom filters, and how can we use them?

We can construct our own filters with AngularJS. This is accomplished by linking the filter to our module. Custom filters are the name for these types of filters.

 

The following code uses a filter to count the number of items in a string:

  angular.module('myCountFilterApp', [])
   .filter('count',function()
{
    return(function(input)
    {
        var out=[];
        out=input.split(',');
        return out.length;
    })
});

 

In the above example, if the string is "21, 34, 45," then the outcome after applying the filter will be 3.

 

14. What role does track by play in the ng-repeat directive?

The ng-repeat directive helps to keep track of all DOM elements dynamically to speed up DOM creation and rendering. Every time a new element is added to the list or collection, the object's instances are stored. AngularJS merely renders the newly inserted element rather than re-rendering the entire collection. This reduces the time it takes for the elements to render.

 

When utilizing ng-repeat on a collection of objects with a unique identifier, new element tracking should be done using that identifier rather than new instance insertion. This may be performed by utilizing the ng-repeat track. For instance, consider the following code:

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


The id of the object is used to track new elements.

 

15. In AngularJS, what is the difference between compile and link?

Compile is a service that traverses HTML in search of all directives and returns link functions.

The link connects the model to a view, allowing any changes to the model to be reflected in the view and vice versa.

 

16. In AngularJS, how does routing work?

Routing allows us to create unique URLs for different parts of our program, allowing users to save the information that best suits their needs. The route is the web address that you can save to your favourites. Routing is especially useful in the creation of SPAs (Single Page Applications), in which a single HTML page is built and dynamically modified as the user interacts.

The "ngRoute" routing module in AngularJS assists with routing. The URL determines how this module works. When a user requests a specific route/URL, the module's routing engine, also known as $routeProvider, generates the view for that URL and determines which controller should handle it, all based on the routing rules set.

Consider the following example:

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: "/"
   });
})

 

We can see from the above example that we need to follow the steps below to establish routing:

  • Pass 'ngRoute' as the dependant module while building the application module, as seen below:
     
var myApp = angular.module('routingExample', ['ngRoute']);

 

  • Then, using the config() function and the $routeProvider service as the dependency, create the routing rules for the application module.
  • The $routeProvider.when(path, route) method is used to configure routing rules. The first parameter is the request URL, and the second specifies the object containing the template, controller, and other property details that must function when the URL is requested.
  • If the user requests "/login-page.html," inject login-page.html into the view and use the loginPageController, as shown in the example.
  • The:empName parameter in the URL "/employee/:empName" refers to the URL parameter dynamically produced in the URL.
  • For any other requests that are not part of the rules configured, the else() method is used to redirect to the default or base URL.

 

17. In AngularJS, write a syntax to send a sample HTTP POST request.

The $http service is used by AngularJS to make any AJAX calls. The following is the syntax:

$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
      });

 

18. Is it feasible to make controllers that are nested?

In AngularJS, it is possible to create nested controllers.

The following is an example code snippet:

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

 

19. What are AngularJS filters, and how do you use them?

Filters in AngularJS are primarily used to format an expression before presenting it to the user. These can be used in controllers, services, and views, among other places. AngularJS comes with several built-in filters, such as currency, filter, date, JSON, limitTo, and so on, whose aim is to format data without affecting its value before merging it with the expression. This is accomplished by using the pipe character (|). AngularJS also allows you to register and construct custom filters, which you can then utilise with the pipe symbol.

Syntax for using filters:

{{expression | filterName:filterInputParameter }}

 

To format data so that the currency sign appears before a salary amount of 18000, for example:

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

 

"Rs.18,000" will be displayed as the salary. 'Rs.' is the currency filter's input to define formatting. If no value is supplied, Dollars ($) is used as the default.

 

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

The scope lifecycle in AngularJS is depicted in the picture below:

Source: Scope Lifecycle in AngularJS

 

  • Creation: During the application bootstrap, $injector creates the rootScope during this phase. New child scopes related to the directives are established during the template linking process.
  • Watcher Registration: The directives in this section register watches on the scope object, which will be used to communicate model values to the DOM.
  • Model Mutation: Model mutations must be present within the scope of the project. For them to be effectively observed, use $apply(). When working on synchronous or asynchronous work requests, AngularJS will take care of these for you.
  • Mutation Observation: Following the completion of the $apply, the digest cycle begins to look for any model modifications on the scopes. The $watches expressions are checked for model modifications, and if any are found, the model's $watch listener is invoked.
  • Scope destruction: When the child scopes are no longer required, the creator of the scopes must destroy them using a scope. $destruct(). This stops the $digest cycle from propagating and frees up memory that was previously consumed by the child scopes.

 

21. How will you make an AngularJS application perform better?

The following two ways for performance optimisation in the production environment have been advocated by the AngularJS creators. They are as follows:

  • Enable strict DI mode: This may be done by using the ngStrictDi directive, which can be written as:
<html ng-app=“myFirstApp” ng-strict-di></html>

 

  • Disable debug data: As demonstrated below, the debugInfoEnabled function of the $compileProvider service can be used to disable debug data:
app.config(function ($compileProvider) {
     $compileProvider.debugInfoEnabled(false);
});

 

Apart from the two, the following suggestions can help us increase our performance:

  • When at all possible, use one-time binding.
  • $httpProvider is made to leverage the applyAsync functionality. – – By avoiding creating too many $watches unnecessarily, the digest cycle will be lengthened, slowing down the process.
  • If you have cases where you need to repeat data calculations, you can use the $cacheFactory directive to save the data and avoid recalculations.
  • If we have a massive number of elements to loop over, we may use pagination or infinite scrolling to decrease the data load instead of loading everything at once. The ngInfiniteScroll directive in AngularJS is used to implement the endless scroll feature.

 

22. How do you achieve internationalization?

Internationalization is a method of displaying material that is specific to a particular country or region in our applications. For example, in the United Kingdom, a website must be displayed in English. However, in India, the same website must be displayed in Hindi. We ensure that our website reaches a larger target audience by including multilingual support in our platform.

 

The angular-translate module, which provides many filters and directives and can import i18n-based data asynchronously, is used to support internationalization in AngularJS. By utilising the highly flexible MessageFormat, the module also supports pluralisation.

 

23. What lifecycle hooks are available?

The following are some of the lifecycle hooks accessible in AngularJS:

  • ngOnInit(): This is a callback method that is called the first time the change detector detects any scope model changes and before any view is checked. When the directive is instantiated, this function is only called once.
  • ngOnChanges(): This callback method is called whenever AngularJS detects changes in the scope model, and it allows us to specify the actions that should be taken in response to those changes. It is called before ngOnInit() when the directive is instantiated, and it is also called whenever the scope model changes.
  • ngDoCheck(): This callback method performs change detection and is only called after the default change detector has completed its duty.
  • ngAfterContentInit(): This function is only called once, and it is called as soon as AngularJS has finished initialising all of the directives' content.
  • ngAfterContentChecked(): This callback method is called after the default change-detector has finished inspecting the directives' content.
  • ngOnDestroy(): ngOnDestroy() cleans up any component immediately before the directives or properties are destroyed. They're useful for avoiding memory leaks and unsubscribing any observables that aren't needed.
  • ngAfterViewChecked(): ngAfterViewChecked() is called as soon as the default change-detector completes one change-check cycle.

 

24. In AngularJS, how do you keep track of logs?

The $log built-in service in AngularJS can be used to keep track of logs. In the event of any unforeseen scenarios, these are mainly utilised for troubleshooting and debugging. They are primarily accomplished using the following methods:

 

  • To log a message to the console, use the log() function. $log.log('Entered some function') is an example of how to use it.
  • info() is a function that allows you to write any message that contains information. $log.info('Data processed successfully') as an example
  • warn() is used to keep track of warnings. $log.warn('The value is empty.') as an example
  • To log errors, use the error() function. $log.error('Oh oh!') is an example of how to use it. 'Something went horribly wrong.')
  • debug() is a debugging function that logs any debug messages. $log.debug('Processed a variable A.') is an example of how to use it.

Key takeaway

In this article, We've covered the most popular AngularJS questions. AngularJS was intended to establish the concept of dependency injection and make single-page application development easier. Even though AngularJS is the initial version, many firms have chosen it due to its numerous advantages, ease of configuration, and extensibility. AngularJS has been the most effective framework for designing online apps in many industries, even though it has undergone many modifications in its various versions and releases.

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think