30 AngularJS Interview Questions And Answers

avatar-image
Misna V.K.
Nov 1, 20238 minutes read

AngularJS is one of the most promising languages. Rich in feature set, this technology is worth to work hard for. Below is the list of super 30 AngularJS interview questions and answers. These questions have been divided as per levels - beginner, intermediate, and advanced.

Beginner AngularJS interview questions

Below is the list of AngularJS interview questions for beginners.

1. What is the syntax of ForEach loop? which loop would you use to parse a JSON and why?

Below is the syntax of for each loop:

angular.ForEach(students,function(value,key)
{
    //some code
}

To parse JSON, we can use any loop, but I would use for each loop because it will minimize my code by eliminating the need to store the length of a JSON in a variable.

2. Explain MVC in reference to angular?

AngularJs is an MVC based framework, where Model for a controller contains data, the controller for a view contains the logic to manipulate that data, and the view is the HTML that displays the data.

A $scope can be considered as a model, whereas the functions written in angular controller modifies the $scope and HTML display the value of the scope variable.

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

4. Can there be two ng-app for a single angular application?

No, there can't be more than one ng-apps for a single AngularJS application.
The ng-app directive conveys AngularJS application that it is the root element. In your HTML document, you can have a single ng-app directive only. In case of more than one ng-app directives, the first appearance will be used.

5. What is $scope?

$scope is a model for a controller and helps the controller in interacting with the view.

(This is a super short answer to this question, but it is complete in every sense. Try not to put any additional angular terms).

6. Name a few inbuilt angular filters?

Currency, lowercase, uppercase, number, date are few inbuilt angular filters.

{{nameOfStudent|uppercase}}

Intermediate AngularJS Interview Questions

Let us take a look at some mid-level AngularJS interview questions

7. What are custom filters? Write down a syntax of the same?

With AngularJS we can create our own filters. This can be done by associating the filter to our module. These types of filters are called custom filters.

Below is the code to count the number of elements in the string by using filter:

    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 output after applying filter will be 3.

Here is some more information on custom filters.

8. What is the difference between ng-if and ng-show?

Ng-if doesn’t render the portion of DOM element on which it is associated if the specified condition is not met whereas ng-show renders the DOM element but set its CSS property of display to none if the specified condition is not met.

9. What is the purpose of the $watch?

The purpose of $watch is to keep track of the old and new value of the watched expression. Below is the code of using $watch.

 $scope.$watch("checkInDate", function (newValue, oldValue) {
                console.log("I've changed : ", newValue);
            });

10. What is the purpose of $rootScope?

$rootScope helps in communication between different controllers of an application. AngularJS can have only one rootScope for an app.

11. Write down the syntax for sending HTTP request?

  $http({
                    method: "POST",
                    url: "URL",
                    data: JSON.stringify(value),
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8'
                }).then(function (response)
                {
                    // success action
                });

12. Where should one use form action instead of $http for accessing a method on a server?

Form action should be used at a place where the server-side method takes the control to some other view in other word leads to redirection whereas HTTP request should be used where the server method returns some data.

13. What is the purpose of find index in AngularJS and what does it return if no value is found?

Find index returns the position of an element in an object. If the requested element is not found then -1 is returned.

 var index = $scope.items.findIndex(record => record.date =='2018-12-12');

In the above code, index of the object is returned where item.date=2018-12-12.

14. What is ng-init used for?

Ng-init is used in a scenario where we want some action to be done before the initialization of a portion of the DOM element.

15. Can I 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.

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

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

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

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

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

The syntax for creating new data object:

$scope.newDate=new Date();

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

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

23. Can I 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}}

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

Advanced AngularJS Interview Questions

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

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

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

The above code will give an error. Here are more details on scope v/s $scope.

27. Explain this code and possible values of restrict attribute?

.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

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.

Here is more detail on compile and link.

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

Here is more detail on SCE.

30. 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.
1. log()-writes a log message in the console
2. info()-writes an information message
3. warn()-write a warning message
4. error()-writes an error message
5. debug()-writes a debug message

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

Keep calm and practice AngularJS!

Tags:
Marketing
avatar-image
Misna V.K.

HR Blogger

Misna is a seasoned writer and content creator with over 7 years of experience in the field. She is the author of this continually updated career advice blog, serves as an empowering beacon for professional growth, offering readers a wealth of invaluable insights and guidance.

Member since Mar 15, 2021
BLOG

Read Our Latest News

Regularly updated blog offers career advice, from job hunting to workplace success. A valuable resource for professional growth and development.

Popular Tags
Data EntryJobsSkillsTypesWriteYourselfTipsExamplesCTCCompanyCostPrepareTechnicalInterviewLaid Off