Limited Time Offer!

For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!

Enroll Now

Top 50 interview question and answers for Angular JS

AngularJs could be a Javascript ASCII text file front-end framework that’s in the main wont to develop single-page net applications (SPAs). It’s an unceasingly growing and increasing framework that provides higher ways in which for developing net applications. It changes the static hypertext mark-up language to dynamic hypertext mark-up language. Its options like dynamic binding and dependency injection eliminate the necessity for code that we’ve got to put in writing otherwise. AngularJs is chop-chop growing and since of this reason, we’ve got totally different versions of AngularJs with the most recent stable being one.7.7. It’s conjointly necessary to notice that Angular is totally different from AngularJs. It’s AN ASCII text file project which might be freely used and altered by anyone. It extends hypertext mark-up language attributes with Directives, and information is sure with hypertext mark-up language.

In the following context I will discuss all the possible FAQ’s, important questions with their answers. They criterias will definitely help you to crack your interviews and following certification exams. So, let’s not waste any more time and dive to our questions…

  1. What is AngularJS?
what is angularjs

AngularJS is a JavaScript framework used for creating single web page applications. It allows you to use HTML as your template language and enables you to extend HTML’s syntax to express your application’s components clearly.

2. What are the key features of AngularJS?

The key features of AngularJS are:

  • Scope
  • Controller
  • Model
  • View
  • Services
  • Data Binding
  • Directives
  • Filters

Testable

3. Explain function scope in AngularJS

Scope refers to the application model. It acts like a glue between the application controller and the view. Scopes are arranged in a hierarchical structure and impersonate the DOM (Document Object Model) structure of the application. It can watch expressions and propagate events.

4. Explain services in AngularJS

AngularJS services are the singleton objects or functions that are used for carrying out specific tasks. It holds some business logic.

5. What is Angular Expression? Explain the 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 is:

  • 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 generate TypeError or ReferenceError
  • No Control Flow Statements: Loops, conditionals or exceptions cannot be used in an angular expression
  • Filters: You can use filters to format data before displaying it.

6. How can you initialize a select box with options on page load?

You can initialize a select box with options on page load by using ng-init directive.

<div ng-controller = ” apps/dashboard/account ” ng-switch
On = “! ! accounts” ng-init = ” loadData ( ) “>

7. What are directives? Name some of the most commonly used directives in AngularJS application

A directive is something that introduces new syntax. They are like markers on the DOM element, which attaches a special behavior to it. In any AngularJS application, directives are the most important components.

Some of the commonly used directives are:

  • ng-model
  • ng-App
  • ng-bind
  • ng-repeat
  • ng-show

8. How Angular JS routes work?

AngularJS routes enable you to create different URLs for different content in your application. Different URLs for different content enable the user to bookmark URLs to specific content. Each such bookmarkable URL in AngularJS 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 belong to an AngularJS module.

Injecting a value into an AngularJS controller function is done by adding a parameter with the same name as the value

9. What is data binding in AngularJS?

Automatic synchronization of data between the model and view components is referred to as data binding in AngularJS. There are two ways for data binding

  • Data mining in classical template systems
  • Data binding in angular templates

10. What are the benefits of AngularJS?

Benefits of AngularJS are:

  • Registering Callbacks: There is no need to register callbacks. This makes your code simple and easy to debug.
  • Control HTML DOM programmatically: Applications which are created using Angular are not required to manipulate the DOM.
  • Transfer data to and from the UI: AngularJS helps to eliminate almost all of the boilerplate. It can validate the form, display errors, return to an internal model, and so on.

No initialization code: With AngularJS, you can bootstrap your app easily. You can use auto injected services into your application in Guice.

11. What is string interpolation in Angular.JS?

In Angular.js, the compiler during the compilation process matches text and attributes. It uses interpolate service to see if they contain embedded expressions. As part of the normal digest cycle, these expressions are updated and registered as watches.

12. What are the steps for the compilation process of HTML?

Compilation of HTML process occurs in the following ways

Using the standard browser API, first, the HTML is parsed into DOM

By using the call to the $compile () method, a compilation of the DOM is performed. The method traverses the DOM and matches the directives.

Link the template with a scope by calling the linking function returned from the previous step

13. Explain directives and their types

During compilation process, when specific HTML function is triggered, it is referred to as directive. It is executed when the compiler encounters it in the DOM.

Different types of directives are:

  • Element directives
  • Attribute directives
  • CSS class directives
  • Comment directives.

14. Explain the linking function and its types

Link combines the directives with a scope and produces a live view. For registering DOM listeners as well as for updating the DOM, link function is responsible. After the template is cloned, it is executed.

  • Pre-linking function: Pre-linking function is executed before the child elements are linked. It is not considered as a safe way for DOM transformation.
  • Post linking function: Post linking function is executed after the child elements are linked. It is safe to do DOM transformation by post-linking function

15. Explain injector in AngularJS

An injector is a service locator. It is used to retrieve object instances as defined by provider, instantiate types, invoke methods, and load modules. There is a single injector per Angular application, it helps to lookup an object instance by its name.

16. What is the main difference between a link and compile in Angular.js?

Compile function: It is used for template DOM manipulation and collects all of the directives.

Link function: It is used for registering DOM listeners as well as for instance, DOM manipulation. It is executed once the template has been cloned.

17. What is the factory function in AngularJS?

For creating the directive, factory method is used. It is invoked only once when the compiler matches the directive for the first time. By using $injector.invoke the factory method is invoked.

18. Explain the styling form that ngModel adds to CSS classes

NgModel adds these CSS classes to allow styling of form. Validation classes of AngularJS are:

  • ng- valid
  • ng- invalid
  • ng-pristine
  • ng-dirty

19. What are the characteristics of “Scope”?

To observer model mutations scopes provide APIs ($watch)

To propagate any model changes through the system into the view from outside of the Angular realm

A scope inherits properties from its parent scope, while providing access to shared model properties, scopes can be nested to isolate application components

Scope provides context against which expressions are evaluated

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

21.  What are the controllers in AngularJS?

Controllers are JavaScript functions which are used to provide data and logic to HTML UI. It acts as an interface between Server and HTML UI. Each controller accepts $scope as a parameter which refers to the application/module that controller is going to control. For example:

<script>  
var app = angular.module('myApp', []);      
app.controller('myCtrl', function($scope) {      
    $scope.firstName = "Aryan";      
    $scope.lastName = "Khanna";      
});      
</script>  

22. What are the uses of controllers in AngularJS?

AngularJS controllers are used for:

  • Setting the initial state of the $scope object
  • Adding behavior to the $scope object

23.  What is the module in AngularJS?

A module is a container for the different parts of the application like a controller, services, filters, directives, etc. It is treated as a main() method. All the dependencies of applications are generally defined in modules only. A module is created using an angular object’s module() method. For example:

var app = angular.module(‘myApp’, []); 

24.  What are the expressions in AngularJS?

Expressions in AngularJS are the code snippets that resolve to a value. AngularJS expressions are placed inside {{expression}}. Expressions are included in the HTML elements.

AngularJS expressions can also contain various valid expressions similar to JavaScript expressions. We can also use the operators between numbers, including strings, literals, objects, and arrays inside the expression {{ }}.

For example:

{{1+1}}  
{{Name + " " + email}} (string)  
{{ Country.Name }} (object)  
{{ fact[4] }} (array)  

25. What is the use of filter in AngularJS?

A filter is used to format the value of the expression to display the formatted output. AngularJS allows us to write our own filter. Filters can be added to expressions by using the pipe character |, followed by a filter. For example:

<div ng-app="myApp" ng-controller="personCtrl">  
<p>The name is {{ firstName | uppercase }}</p>  
</div>  
<script>  
angular.module('myApp', []).controller('personCtrl', function($scope) {      
    $scope.firstName = "Sonoo",      
    $scope.lastName = "Jaiswal"      
});      
</script>  

Filters can be applied in view templates, controllers, services and directives. It is important to know that filters are case-sensitive. There are some built-in filters provided by AngularJS such as Currency, Date, Filter, JSON, Limit, Lowercase, Number, Orderby, and Uppercase.

26. What do you know about uppercase filter and lowercase filter in AngularJS?

Uppercase filters are used to convert a text to upper case text. For example:

Type first name:<input type = "text" ng-model = "student.firstName">  
Type last name: <input type = "text" ng-model = "student.lastName">  
Name in Upper Case: {{student.fullName() | uppercase}}  

In above example, uppercase filter is added to an expression using pipe character. It will print student name in capital letters.

On the other side, lowercase filters are used to convert a text to lower case text. For example:

Type first name:<input type = "text" ng-model = "student.firstName">  
Type last name: <input type = "text" ng-model = "student.lastName">  
Name in Upper Case: {{student.fullName() | lowercase}}  
It will print student name in lowercase letters.

27. Explain custom filters with an example.

We can create our own filters in AngularJS. It can be performed by associating the filter to our module. These types of filters are known as custom filters.

An example given below can be used to count the number of elements in the string by using the filter:

angular.module('myCountFilterApp', [])  
   .filter('count',function()  
{  
    return(function(input)  
    {  
        var out=[];  
        out=input.split(',');  
        return out.length;  
    })  
});  
As per above example, if the string is "21, 34, 45" then output after applying filter will be 3.

28. Explain Currency filter in AngularJS. How can we use it?

The currency filter contains the “$” Dollar symbol as default. We can apply the following code as the html template format of Currency Filter.

{{ currency_expression | currency : symbol : fractionSize}}  

We can use Currency Filter by using the following methods:

Default                                  

If we do not provide any currency symbol, then Dollar sign will be used by default as shown below:

<!-- by default -->
Default Currency{{amount | currency}}
User-Defined

To use different types of currency symbols, we have to define our own symbol by applying the Hexa-Decimal code or Unicode of that Currency.

E.g., to define Indian Currency Symbol, then we have to use Unicode-value or Hexa-Decimal value.

Indian Currency {{amount | currency:”&# 8377″}}

29. What do you understand by Dependency Injection in AngularJS?

Dependency Injection (also called DI) is one of the best features of AngularJS. It is a software design pattern where objects are passed as dependencies rather than hard coding them within the component. It is useful for removing hard-coded dependencies and making dependencies configurable. To retrieve the required elements of the application that need to be configured when the module is loaded, the “config” operation uses Dependency Injection. It allows separating the concerns of different components in an application and provides a way to inject the dependent component into the client component. By using Dependency Injection, we can make components maintainable, reusable, and testable.

A simple case of dependency injection in AngularJS is shown below:

myApp.controller('myController', function ($scope, $http, $location)  
    {  
        //logic   
    });  
Here, a controller is declared with its dependencies.

AngularJS provides the following core components which can be injected into each other as dependencies:

  • Value
  • Factory
  • Service
  • Provider
  • Constant

30. What do you understand by validation of data in AngularJS?

AngularJS enriches form filling and validation. AngularJS provides client-side form validation. It checks the state of the form and input fields (input, text-area, select), and notify the user about the current state. It also holds the information about whether the input fields have been touched, or modified, or not.

There are following directives that can be used to track error:

$dirty

It states that the value has been changed.

$invalid

It states that the value which is entered is invalid.

$error

It states the exact error.

Moreover, we can use no validate with a form declaration to disable the browser’s native form validation.

31. What do you understand by linking function? Explain its type.

Link is used for combining the directives with a scope and producing a live view. The link function is used for registering DOM listeners as well as updating the DOM. The linking function is executed as soon as the template is cloned.

There are two types of linking function:

  • Pre linking function
  • Pre-linking functions are executed before the child elements are linked. This method is not considered as a safe way for DOM transformation.
  • Post linking function
  • Post-linking functions are executed after the child elements are linked. This method is a safe way for DOM transformation.

32. What do you know about injector?

An injector is referred to as a service locator. It is used to receive object instances as defined by the providers, invoke methods, instantiate types, and load modules. Each Angular application consists of a single injector which helps to look upon an instance by its name.

33. What is the factory method in AngularJS?

Factory method is used for creating a directive. Whenever the compiler matches the directive for the first time, the factory method is invoked. Factory method is invoked using $injector.invoke.

Syntax
module.factory('factoryName', function);  

34. How will you explain the concept of hierarchy? How many scopes can an application have?

Each Angular application contains one root scope, but there can be several child scopes. The application may have multiple scopes because child controllers and some directives create new child scopes. When the new scope is formed or created, it is added as a child of the parent scope. As similar to DOM, scopes also create a hierarchical structure.

35. Explain how logs are maintained in AngularJS?

Logs can be maintained using $log service. The main purpose of $log service is to help in debugging and troubleshooting. It is done with the help of the following methods.

  • log()- It writes a log message in the console.
  • info()- It writes an information message.
  • warn()- It writes a warning message.
  • error()- It writes an error message.
  • debug()- It writes a debug message.

$log.error(‘this will displayed as an error in console’)

36. Can you set an angular variable from PHP session variable without sending an HTTP request?

Yes, we can do that by injecting PHP in the required place.

$scope.name='<?= $session['name'] ?>';

This will work only if you are using PHP to render the HTML and the above javascript is writter in <script> tag inside the php file.

37. What is the significance of pipe operator in angularJs and What would be the result of following expression

{{ Somevalue|lowercase|uppercase}}

Pipe operator in AngularJS represents filters that are used on the expression. The preference order is from left to right. So, the result of the above expression would be SOMEVALUE.

38. Explain the following code:

<div ng-repeat="hotel in hotels|filter:setFinalFilter|orderBy : 'minPrice'">{{hotel.name}}</div>

Here, setFinalFilter is a custom filter used on the hotels object. The result would display the name of filtered hotels in ascending order of their minPrice.

39. What is service in AngularJS used for?

Services in AngularJS are objects which are used to communicate within entire applications.

app.service('sharedData', function () {
 //methods to get and set variable
    });

40. What is dependency injection and what are the benefits of it?

Dependency injection is a powerful design pattern that allows separating the concerns of different components in an application and provides a way to inject the dependent component into the client component.

Consider the below code:

myApp.controller('myController', function ($scope, $http, $location)
    {
        //logic 
    });

Here, a controller is declared with its dependencies.

.$http, $location are all services which are injected into the controller as a dependent entity. All of them have some independent specific task associated with it. MyController does not need to create their instance, but it can directly use them.

41. Write down the syntax of creating a new date object?

The syntax for creating new data object:

$scope.newDate=new Date();

42. Can parent controller access the methods of child controller or vice versa?

No, the parent controller cannot access the methods of child controller, but the child controller can access the methods of the parent controller.

Evaluate the feasibility of the following code:

<select ng-options="student.name for student in students"></select>

This code will give a syntax error. We cannot use ng-options without ng-model. Using the array or object obtained by evaluating the ngOptions expression, the ngOptions attribute dynamically generates a list of < option > elements for the < select > element. On selecting an item in the < select > menu, the array element or object property will be bound to the model identified by the ngModel directive. Hence, ng-model is must with ng-options.

43. Can you use ternary operator in angular expression?

Yes, ternary operators or no flow operators can be used in an angular expression.

{{name==undefined:'no name specified'?name}}

44. When is $location used? Explain with some scenario.

$location is an angular service which keeps track of the URL of the application and makes it available to a controller. If $location is changed from the controller, the impact is reflected in the address bar, and vice versa is also true.

45. Explain the purpose of track by in ng-repeat?

In AngularJS, directives like ng-repeat keep track of all the elements to minimize the DOM creation. It does that by storing the object instance when a new element is added to the collection. Angular does not re-render the entire element set; it just renders the new element.

When ng-repeats is used with the object having some unique id, the tracking should be done by that identifier, instead of the object instance. Consider the below code.

item in items track by item.id

Here, tracking is done based on item id.

46. How is scope in directive different from scope in controller?

Both $scope and scope are instances of scope object. The difference lies in the name that is used for them. In order to explain the difference between $scope and scope, we need to know about directives with an isolated scope.

Let us try to understand this with the following code:

.directive('testDirective', function() {
  return {
    scope: {},
    link: function(myScopeVar, elem,attr) {
      console.log(scope)
    }
  }
})
})

In the above code, a directive with an isolated scope is declared. The link used in above code is a regular Javascript function with signature scope, element and attribute. The name of scope object is not important because whatever name you give to this element, it will be linked to the directive’s scope object. That is why, using myScopeVar will not give any error. The $scope, on other hand, cannot be used with any other name.

For further clarification, let us see the following code:

.
}); directive('myCustomer', function() {
  return {
    restrict: 'E',
    scope: {
      customerInfo: '=info'
    },
    templateUrl: 'my-customer.html'
  };

Here, a custom directive of name myCustomer is declared. The directive is restricted to element name only. The directive has its own isolated scope which has a property customerInfo and takes its value from info attribute of the myCustomer element.

The template/view of the directive is my-customer.html. The possible declaration of this directive would be .

The possible values of restrict can be:

‘A’ – only matches attribute name

‘E’ – only matches element name

‘C’ – only matches the class name

‘M’ – only matches the comment

47. What is the difference between compile and link?

Compile can be considered as a service which traverses the HTML, find for all the directives and returns a link function.

Link, on the other hand, combines the model with a view. Any change in model reflects the change in view and any change in view reflects in the model.

48. Explain strict conceptual escaping?

AngularJS treats all values as untrusted/unsecured by default in HTML or sensitive URL bindings. When binding untrusted values, AngularJS will automatically run security checks on them (sanitizations, whitelists, depending on context), or throw an error when it cannot guarantee the security of the result. This behavior depends strongly on contexts: HTML can be sanitized, but template URLs cannot.

To illustrate this, consider the ng-bind-html directive. It renders its value directly as HTML. When given an untrusted input, AngularJS will attempt to sanitize it before rendering if a sanitizer is available. To bypass sanitization and render the input as-is, you will need to mark it as trusted.

49.How logs are maintained in AngularJS?

The follow-up question can be how to Blackbox AngularJS source in the browser and which all browser supports Blackbox?

Logs are maintained with the help of $log service. The main purpose of this service is to help in debugging and troubleshooting. This is done with the help of four methods.

  • log()-writes a log message in the console
  • info()-writes an information message
  • warn()-write a warning message
  • error()-writes an error message
  • debug()-writes a debug message

$log.error(‘this will displayed as an error in console’)

50. What is two-way binding? Two-way binding means that when data in the view is changed the underlying model gets updated automatically and when a model from the controller is changed the view gets updated.

This was the end of the FAQ series. Hope this would be enough to crack your interview! For gaining more knowledge in DevOps, Cloud and containers, visit DevOpsSchool website. There you will get many courses and tools training under experienced trainers, experts and professionals.

Rajesh Kumar
Follow me
Latest posts by Rajesh Kumar (see all)
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x