Question Mentor Logo Question Mentor
Practice With AI
Home » Directory » Interview Preparation » 100 Top-Asked AngularJS Interview Questions in 2026

100 Top-Asked AngularJS Interview Questions in 2026

Having worked with legacy AngularJS systems well into 2026, I’ve noticed a surprising trend: despite its official end-of-life in 2021, AngularJS still surfaces in interviews, especially for roles involving maintenance, migration, or enterprise support.

Many large organizations haven’t fully migrated yet, and hiring managers often test for deep AngularJS knowledge to assess troubleshooting and refactoring skills. In fact, several clients this year specifically requested AngularJS screening questions to evaluate candidates for legacy code modernization.

So while new projects overwhelmingly use modern Angular or other frameworks, the demand for understanding AngularJS fundamentals, pitfalls, and upgrade paths remains real, making a focused list of the 100 top-asked AngularJS interview questions in 2026 genuinely valuable for certain career tracks.

Here are the 100 Top-Asked AngularJS Interview Questions…

100 Top Asked AngularJS Interview Questions in 2026

1. What is AngularJS?

AngularJS is an open-source, JavaScript-based framework primarily used for building dynamic, single-page applications (SPAs). Developed to simplify both the development and testing of web applications, AngularJS extends HTML with new attributes and directives, enabling developers to create rich, interactive user interfaces.

It follows the Model-View-Controller (MVC) architectural pattern, which helps organize code into logical components. AngularJS is particularly powerful for creating real-time applications where data updates frequently, such as dashboards or social media platforms.

AngularJS is often confused with its successor, Angular, which is a complete rewrite of the framework. While AngularJS is based on JavaScript, Angular is built using TypeScript.

2. Who developed AngularJS and when?

AngularJS was developed by Miško Hevery and Adam Abrons in 2009. It was later adopted and maintained by Google, which significantly contributed to its growth and popularity in the developer community.

The framework was designed to address challenges in building dynamic web applications, particularly the complexity of managing data binding and DOM manipulation manually.

3. What are the key features of AngularJS?

AngularJS offers several powerful features that make it a preferred choice for building dynamic web applications:

  • Two-Way Data Binding: Automatically synchronizes data between the model and the view, reducing the need for manual DOM manipulation.
  • Directives: Extends HTML with custom attributes and elements, allowing developers to create reusable components.
  • Dependency Injection (DI): Simplifies the process of managing dependencies, making the code more modular and easier to test.
  • MVC Architecture: Encourages a clean separation of concerns by dividing the application into Model, View, and Controller components.
  • Templates: Uses HTML to define the user interface, making it intuitive for developers familiar with web technologies.
  • Routing: Supports single-page application navigation through client-side routing.
  • Testing: Built with testability in mind, providing tools for unit testing and end-to-end testing.

4. Explain the difference between AngularJS and Angular.

While AngularJS and Angular share the same core philosophy, they are fundamentally different frameworks. Here’s a breakdown of their key differences:

  • Language: AngularJS is based on JavaScript, while Angular is built using TypeScript, a superset of JavaScript.
  • Architecture: AngularJS uses the MVC (Model-View-Controller) pattern, whereas Angular follows a component-based architecture.
  • Performance: Angular is significantly faster and more efficient due to its modern design and optimizations like Ahead-of-Time (AOT) compilation.
  • Mobile Support: Angular is designed with mobile applications in mind, while AngularJS was primarily focused on desktop web applications.
  • Data Binding: AngularJS uses two-way data binding by default, while Angular offers both one-way and two-way data binding.
  • Dependency Injection: Angular has a more robust and hierarchical dependency injection system compared to AngularJS.

In summary, Angular is a complete rewrite of AngularJS, designed to address its limitations and provide a more scalable and performant framework for modern web development.

5. What is data binding in AngularJS?

Data binding in AngularJS is the automatic synchronization of data between the model (application data) and the view (user interface). It eliminates the need for manual DOM manipulation, making the development process more efficient and less error-prone.

AngularJS supports two types of data binding:

  • One-Way Data Binding: Data flows in one direction, either from the model to the view or vice versa. This is typically used for displaying data.
  • Two-Way Data Binding: Data flows in both directions. Changes in the model are reflected in the view, and changes in the view are automatically updated in the model.

Data binding is a core feature of AngularJS, enabling developers to create dynamic and responsive applications with minimal code.

6. Describe two-way data binding in AngularJS.

Two-way data binding in AngularJS is a mechanism where the model and the view are always in sync. When the model changes, the view updates automatically, and when the view changes (e.g., through user input), the model is updated as well.

This is achieved using the ng-model directive. For example, if you bind an input field to a model property using ng-model, any changes made to the input field will immediately update the model, and vice versa.


<input type="text" ng-model="user.name">
<p>Hello, {{user.name}}!</p>
        

In this example, typing in the input field updates the user.name model, and the paragraph displays the updated value in real-time.

7. What are directives in AngularJS?

Directives in AngularJS are markers on DOM elements (such as attributes, elements, or CSS classes) that tell AngularJS’s HTML compiler to attach a specified behavior to that element or even transform the element and its children. They extend HTML’s functionality, allowing developers to create reusable components and manipulate the DOM in a declarative way.

Directives can be built-in or custom. They are a powerful feature that enables developers to encapsulate complex logic and behavior into simple, reusable HTML elements or attributes.

8. Name some built-in directives in AngularJS.

AngularJS provides a variety of built-in directives that simplify common tasks. Here are some of the most commonly used ones:

  • ng-app: Defines the root element of an AngularJS application.
  • ng-model: Binds the value of HTML controls (input, select, textarea) to application data.
  • ng-bind: Binds application data to the HTML view.
  • ng-repeat: Repeats a set of HTML elements for each item in a collection.
  • ng-if: Conditionally includes or excludes HTML elements based on an expression.
  • ng-show / ng-hide: Shows or hides HTML elements based on an expression.
  • ng-click: Specifies custom behavior when an element is clicked.
  • ng-class: Dynamically applies CSS classes based on an expression.

9. How do you create a custom directive in AngularJS?

Creating a custom directive in AngularJS involves defining a new directive using the directive function provided by the AngularJS module. Here’s a step-by-step guide:

  1. Define a module and inject the $compile and $rootScope services if needed.
  2. Use the directive method to register your custom directive.
  3. Return a directive definition object that specifies the directive’s behavior, template, and scope.

angular.module('myApp', [])
  .directive('myDirective', function() {
    return {
      restrict: 'E', // Restricts the directive to an element
      template: '<h1>Hello, {{name}}!</h1>',
      scope: {
        name: '@' // Isolates the scope and binds the 'name' attribute
      }
    };
  });
        

In this example, <my-directive name="World"></my-directive> will render as <h1>Hello, World!</h1>.

10. What is the restrict option in custom directives?

The restrict option in a custom directive specifies how the directive can be used in HTML. It determines whether the directive can be invoked as an element, attribute, class, or comment.

The restrict property can take the following values:

  • 'E': Restricts the directive to be used as an element (e.g., <my-directive></my-directive>).
  • 'A': Restricts the directive to be used as an attribute (e.g., <div my-directive></div>).
  • 'C': Restricts the directive to be used as a class (e.g., <div class="my-directive"></div>).
  • 'M': Restricts the directive to be used as a comment (e.g., <!-- directive: my-directive -->).

By default, if restrict is not specified, the directive can be used as an attribute or element.

In AngularJS directives, the compile and link functions are used to manipulate the DOM and bind behavior to elements. They serve different purposes in the directive lifecycle:

  • Compile Function: This function is responsible for DOM manipulation and template cloning. It runs once when the directive is first encountered, before any data is bound to the scope. It is used for transforming the DOM, such as adding or removing elements, and returns a link function. The compile function is ideal for optimizing performance when you need to manipulate the DOM before linking it to a scope.
  • Link Function: The link function is responsible for registering event listeners and watching for changes in the data. It runs after the template has been cloned and is where most of the directive’s logic resides. The link function can access the scope, element, and attributes, allowing you to bind data and define behavior.

angular.module('myApp', [])
  .directive('myDirective', function() {
    return {
      compile: function(tElement, tAttrs) {
        // DOM manipulation here
        console.log('Compile phase');
        return {
          pre: function(scope, element, attrs) {
            // Pre-link logic (rarely used)
          },
          post: function(scope, element, attrs) {
            // Post-link logic (most common)
            console.log('Link phase');
          }
        };
      }
    };
  });
        

In most cases, you’ll use the link function for binding data and defining behavior, while the compile function is used for more advanced DOM transformations.

12. What is transclusion in AngularJS directives?

Transclusion in AngularJS directives allows you to wrap the content of a directive around the content provided by the user. It enables the creation of reusable components that can encapsulate arbitrary content. Transclusion is particularly useful for creating directives like modals, tabs, or accordions, where the directive provides the structure, and the user provides the content.

To enable transclusion, set the transclude property to true in the directive definition object. You can then include the transcluded content in your directive’s template using the ng-transclude directive.


angular.module('myApp', [])
  .directive('myDirective', function() {
    return {
      transclude: true,
      template: '<div>This is a directive: <ng-transclude></ng-transclude></div>'
    };
  });
        

In this example, any content inside <my-directive></my-directive> will be inserted where <ng-transclude></ng-transclude> is placed.

13. What is scope in AngularJS?

In AngularJS, the scope is an object that acts as a binding layer between the view (HTML) and the controller (JavaScript). It holds the application data and provides a context for expressions and directives. Scopes are organized in a hierarchical structure, which mirrors the DOM structure of the application.

The scope is responsible for detecting changes in the model and updating the view accordingly, and vice versa. It also provides methods like $watch to observe model changes and $apply to propagate changes from outside the AngularJS context.

14. Explain the difference between $scope and $rootScope.

In AngularJS, $scope and $rootScope are objects that provide a context for data binding, but they serve different purposes:

  • $scope: This is a local scope associated with a specific controller or directive. Each controller has its own $scope, which is a child of the $rootScope. It is used to share data between the view and the controller.
  • $rootScope: This is the top-level scope in an AngularJS application. It is available globally and can be used to share data across the entire application. Variables and functions defined on the $rootScope are accessible from any $scope in the application.

While $scope is specific to a particular part of the application, $rootScope is a singleton object that is available throughout the application.

15. What is the scope hierarchy in AngularJS?

The scope hierarchy in AngularJS is a tree-like structure that mirrors the DOM hierarchy of the application. Each AngularJS application has a single $rootScope, and each controller or directive can have its own child scope. Child scopes prototypally inherit from their parent scopes, allowing them to access properties and methods defined in their parent scopes.

When a property is accessed in a scope, AngularJS first looks for it in the current scope. If it is not found, it traverses up the scope hierarchy until it finds the property or reaches the $rootScope.

This hierarchy enables data sharing and encapsulation, making it easier to manage complex applications.

16. How does prototypal inheritance work with scopes?

Prototypal inheritance in AngularJS scopes means that child scopes inherit properties and methods from their parent scopes. If a property is not found in the current scope, AngularJS looks up the scope hierarchy until it finds the property or reaches the $rootScope.

This inheritance model allows for efficient data sharing and encapsulation. However, it can lead to unexpected behavior if not understood properly. For example, if a child scope modifies a primitive value inherited from a parent scope, it creates a new property in the child scope instead of modifying the parent scope’s property. To avoid this, it’s recommended to use objects for model data, as changes to object properties are reflected in both the parent and child scopes.


// Parent scope
$scope.parentData = { value: 'Hello' };

// Child scope
$scope.childData = $scope.parentData;
$scope.childData.value = 'World'; // Modifies the parent scope's property
        

17. What are controllers in AngularJS?

Controllers in AngularJS are JavaScript functions that provide data and logic to HTML views. They are responsible for initializing the scope and defining the behavior of the view. Controllers are typically attached to the DOM via the ng-controller directive.

Controllers are used to:

  • Set up the initial state of the scope.
  • Define functions and methods for the view to interact with.
  • Handle user input and update the model accordingly.

Controllers should not be used for DOM manipulation or complex business logic, which should be delegated to services or directives.

18. How do you define a controller in AngularJS?

To define a controller in AngularJS, you use the controller method of an AngularJS module. The controller function takes the $scope as a parameter, which is used to expose data and functions to the view.


angular.module('myApp', [])
  .controller('MyController', function($scope) {
    $scope.message = 'Hello, World!';
    $scope.greet = function() {
      alert($scope.message);
    };
  });
        

In this example, MyController defines a message property and a greet function, which can be accessed in the associated view.

19. What is dependency injection in AngularJS?

Dependency Injection (DI) is a design pattern in which an object receives its dependencies from an external source rather than creating them itself. In AngularJS, DI is used to manage the dependencies of components like controllers, services, and directives, making the code more modular, reusable, and easier to test.

AngularJS provides a built-in DI mechanism that automatically resolves and injects dependencies based on their names or annotations.

20. How does dependency injection work in AngularJS?

Dependency Injection in AngularJS works by declaring the dependencies of a component (e.g., controller, service, or directive) as parameters in its constructor function. AngularJS then resolves these dependencies and injects them when the component is instantiated.

There are three ways to specify dependencies:

  • Implicit Annotation: Dependencies are inferred from the parameter names. This method is not recommended for minified code, as the parameter names may change.
    
    function MyController($scope, $http) {
      // Controller logic
    }
                    
  • Inline Array Annotation: Dependencies are specified as an array of strings, followed by the function. This method is minification-safe.
    
    ['$scope', '$http', function($scope, $http) {
      // Controller logic
    }]
                    
  • $inject Property: Dependencies are specified using the $inject property of the function. This method is also minification-safe.
    
    MyController.$inject = ['$scope', '$http'];
    function MyController($scope, $http) {
      // Controller logic
    }
                    

AngularJS’s DI system simplifies the process of managing dependencies, making it easier to write modular and testable code.

21. What are services in AngularJS?

In AngularJS, services are singleton objects that provide specific functionality to your application. They are used to organize and share code across different parts of an application, such as controllers, directives, and other services. Services are typically used for tasks like data fetching, logging, or any reusable logic that needs to be accessed by multiple components.

Services are instantiated only once during the lifetime of an application, making them efficient for maintaining state or sharing data.

AngularJS provides several built-in services, such as $http for making AJAX calls and $q for handling promises. You can also create custom services to encapsulate your application’s logic.

22. Explain the difference between factory, service, and provider.

In AngularJS, factory, service, and provider are all ways to create and configure services, but they differ in how they are defined and instantiated:

  • Factory: A factory is a function that returns an object. You can define the object’s properties and methods within the factory function. Factories are useful when you need to return an object with methods and properties that can be used across your application.
    
    angular.module('myApp').factory('myFactory', function() {
      return {
        greet: function() {
          return 'Hello, World!';
        }
      };
    });
                    
  • Service: A service is a constructor function that is instantiated with the new keyword. It allows you to define properties and methods directly on the this object. Services are useful when you want to create an object with methods that can be reused.
    
    angular.module('myApp').service('myService', function() {
      this.greet = function() {
        return 'Hello, World!';
      };
    });
                    
  • Provider: A provider is the most flexible and configurable way to create a service. It allows you to define a service that can be configured before it is injected. Providers are useful when you need to create a service that requires configuration before it is used.
    
    angular.module('myApp').provider('myProvider', function() {
      this.$get = function() {
        return {
          greet: function() {
            return 'Hello, World!';
          }
        };
      };
    });
                    

In summary, use a factory when you need to return an object, a service when you want to use a constructor function, and a provider when you need configurable services.

23. How do you create a factory in AngularJS?

To create a factory in AngularJS, you use the factory method of an AngularJS module. The factory function should return an object that contains the methods and properties you want to expose.


angular.module('myApp', [])
  .factory('myFactory', function() {
    var message = 'Hello, World!';

    return {
      getMessage: function() {
        return message;
      },
      setMessage: function(newMessage) {
        message = newMessage;
      }
    };
  });
        

In this example, myFactory exposes two methods: getMessage and setMessage. You can inject and use this factory in controllers or other services.

24. How do you create a service in AngularJS?

To create a service in AngularJS, you use the service method of an AngularJS module. The service function acts as a constructor, and you can define properties and methods on the this object.


angular.module('myApp', [])
  .service('myService', function() {
    this.message = 'Hello, World!';

    this.getMessage = function() {
      return this.message;
    };

    this.setMessage = function(newMessage) {
      this.message = newMessage;
    };
  });
        

In this example, myService defines a message property and two methods: getMessage and setMessage. You can inject and use this service in controllers or other components.

25. How do you create a provider in AngularJS?

To create a provider in AngularJS, you use the provider method of an AngularJS module. A provider allows you to define a service that can be configured before it is injected. The $get method of the provider is used to create the service instance.


angular.module('myApp', [])
  .provider('myProvider', function() {
    var message = 'Hello, World!';

    this.setMessage = function(newMessage) {
      message = newMessage;
    };

    this.$get = function() {
      return {
        getMessage: function() {
          return message;
        }
      };
    };
  });
        

In this example, myProvider defines a setMessage method for configuration and a $get method that returns the service instance. You can configure the provider during the configuration phase of your application.

26. What is the $http service in AngularJS?

The $http service in AngularJS is a built-in service used to make AJAX (Asynchronous JavaScript and XML) calls to fetch or send data from/to a server. It simplifies the process of communicating with RESTful APIs and handling asynchronous operations.

The $http service returns a promise, which allows you to handle the response asynchronously using .then() for success and .catch() for errors.

27. How do you make AJAX calls using $http?

To make an AJAX call using the $http service in AngularJS, you typically use the $http method with a configuration object that specifies the request details, such as the URL, method, and data.


angular.module('myApp', [])
  .controller('MyController', function($scope, $http) {
    $http({
      method: 'GET',
      url: 'https://api.example.com/data'
    }).then(function successCallback(response) {
      $scope.data = response.data;
    }, function errorCallback(response) {
      console.error('Error fetching data:', response.status);
    });
  });
        

In this example, an HTTP GET request is made to https://api.example.com/data. The .then() method is used to handle the response, where successCallback processes the successful response, and errorCallback handles any errors.

28. What are promises in AngularJS?

In AngularJS, a promise is an object that represents the eventual result of an asynchronous operation. Promises are used to handle asynchronous tasks, such as AJAX calls, in a more manageable and readable way. A promise can be in one of three states:

  • Pending: The initial state; the operation has not completed yet.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Promises allow you to chain asynchronous operations using methods like .then(), .catch(), and .finally().

29. Explain $q service and deferred objects.

The $q service in AngularJS is a promise/deferred implementation inspired by the Kris Kowal’s Q library. It provides a way to create and manage promises and deferred objects for handling asynchronous operations.

A deferred object represents a task that will finish in the future and provides methods to resolve or reject the associated promise. The $q service allows you to create deferred objects and promises, which can be used to handle asynchronous operations in a structured way.


angular.module('myApp', [])
  .controller('MyController', function($scope, $q) {
    var deferred = $q.defer();

    // Simulate an asynchronous operation
    setTimeout(function() {
      deferred.resolve('Data fetched successfully!');
    }, 1000);

    deferred.promise.then(function(data) {
      $scope.data = data;
    });
  });
        

In this example, a deferred object is created using $q.defer(). The promise is resolved after a delay, and the .then() method is used to handle the resolved data.

30. What is the digest cycle in AngularJS?

The digest cycle in AngularJS is the process by which AngularJS monitors watchers on the scope to detect changes in model values. When a change is detected, AngularJS updates the view to reflect the new model state. The digest cycle is triggered automatically by AngularJS in response to events like user interactions (e.g., clicks, input changes) or AJAX calls.

During the digest cycle, AngularJS evaluates all watchers registered on the scope. If any watcher detects a change, the corresponding listener function is called, and the view is updated. This cycle continues until no more changes are detected or a maximum number of iterations is reached (to prevent infinite loops).

You can manually trigger a digest cycle using $scope.$apply(), which is useful when changes occur outside the AngularJS context (e.g., in a third-party library callback).

31. How does the digest cycle work?

The digest cycle in AngularJS is a process where the framework checks all $watch expressions on the scope to detect changes in model values. When a change is detected, AngularJS updates the corresponding parts of the view. This cycle ensures that the view is always synchronized with the model.

Here’s how it works:

  1. The digest cycle starts when an event (e.g., user interaction, AJAX response) triggers it.
  2. AngularJS evaluates all $watch expressions registered on the scope. If a change is detected, the associated listener function is called.
  3. The cycle repeats until no more changes are detected or a maximum of 10 iterations is reached (to prevent infinite loops).

The digest cycle is a core part of AngularJS’s data binding mechanism, ensuring that the UI is always up-to-date with the latest model changes.

32. What triggers the digest cycle?

The digest cycle in AngularJS is triggered by various events, including:

  • User interactions (e.g., clicking a button, typing in an input field).
  • AJAX calls using $http.
  • Timeouts or intervals created using $timeout or $interval.
  • Manually calling $scope.$apply() or $scope.$digest().
  • Changes to model values within AngularJS’s context (e.g., using ng-model or ng-click).

These triggers ensure that AngularJS is aware of changes and can update the view accordingly.

33. Explain $apply and $digest.

$apply and $digest are methods used to manage the digest cycle in AngularJS:

  • $apply: This method is used to evaluate an expression and trigger a digest cycle. It is typically used when changes occur outside AngularJS’s context (e.g., in a third-party library callback). $apply ensures that the changes are processed by AngularJS and the view is updated.
    
    $scope.$apply(function() {
      $scope.message = "Updated message";
    });
                    
  • $digest: This method triggers a digest cycle for the current scope and its children. It evaluates all watchers and updates the view if changes are detected. Unlike $apply, $digest does not accept an expression.
    
    $scope.$digest();
                    

While $apply is more commonly used, $digest is useful when you need to manually trigger a digest cycle without evaluating an expression.

34. What is $watch in AngularJS?

$watch is a method on the $scope object that allows you to observe changes in a model or expression. When the observed value changes, the associated listener function is called. This is a fundamental part of AngularJS’s data binding and digest cycle.

The $watch method takes two arguments: the expression to watch and the listener function to call when the expression changes.


$scope.$watch('message', function(newValue, oldValue) {
  console.log('Message changed from ' + oldValue + ' to ' + newValue);
});
        

In this example, the listener function is called whenever the message property changes.

35. How do you add a watcher to a scope?

To add a watcher to a scope in AngularJS, you use the $watch method on the $scope object. You specify the expression to watch and the listener function to call when the expression changes.


$scope.$watch('user.name', function(newValue, oldValue) {
  if (newValue !== oldValue) {
    console.log('Name changed to: ' + newValue);
  }
});
        

In this example, a watcher is added to the user.name property. The listener function is called whenever the value of user.name changes.

36. What are filters in AngularJS?

Filters in AngularJS are used to format or transform data before it is displayed in the view. They can be applied to expressions in templates, directives, or controllers. Filters are commonly used for tasks like formatting dates, currencies, or filtering arrays.

AngularJS provides several built-in filters, and you can also create custom filters to suit your application’s needs.

37. Name some built-in filters in AngularJS.

AngularJS includes a variety of built-in filters for common tasks:

  • currency: Formats a number as a currency.
  • date: Formats a date to a specified format.
  • filter: Selects a subset of items from an array.
  • json: Formats an object as a JSON string.
  • limitTo: Limits an array or string into a specified number of elements or characters.
  • lowercase: Converts a string to lowercase.
  • uppercase: Converts a string to uppercase.
  • orderBy: Orders an array by an expression.

Filters can be used in templates using the pipe (|) character.


{{ price | currency }}
{{ date | date:'medium' }}
        

38. How do you create a custom filter?

To create a custom filter in AngularJS, you use the filter method of an AngularJS module. The filter function should return a function that takes the input value and any additional arguments, then returns the transformed value.


angular.module('myApp', [])
  .filter('reverse', function() {
    return function(input) {
      if (input) {
        return input.split('').reverse().join('');
      }
    };
  });
        

In this example, the reverse filter reverses a string. You can use it in a template like this:


{{ 'hello' | reverse }} 
        

39. What is routing in AngularJS?

Routing in AngularJS allows you to create single-page applications (SPAs) with multiple views. It enables navigation between different views without reloading the entire page. Routing is typically used to divide an application into logical sections, each with its own view and controller.

AngularJS provides the ngRoute module for handling routing, which maps URLs to views and controllers.

40. Explain ngRoute module.

The ngRoute module in AngularJS is used to implement routing in single-page applications. It provides services and directives to define routes, map them to views, and associate them with controllers.

To use ngRoute, you need to include it as a dependency in your AngularJS application and configure the routes using the $routeProvider service.


angular.module('myApp', ['ngRoute'])
  .config(function($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'home.html',
        controller: 'HomeController'
      })
      .when('/about', {
        templateUrl: 'about.html',
        controller: 'AboutController'
      })
      .otherwise({
        redirectTo: '/'
      });
  });
        

In this example, the $routeProvider defines routes for the home and about pages. The otherwise method specifies the default route if no other routes match.

The ng-view directive is used in the HTML to display the view associated with the current route.


41. What is $routeProvider?

$routeProvider is a service in AngularJS used to configure routes for your application. It is part of the ngRoute module and allows you to define how different URLs map to specific views and controllers. With $routeProvider, you can set up navigation rules for your single-page application (SPA), enabling users to move between different sections of your app without a full page reload.

You typically configure $routeProvider in the config phase of your AngularJS application.

42. How do you configure routes in AngularJS?

To configure routes in AngularJS, you use the $routeProvider service within the config function of your application module. Here’s how you can define routes:


angular.module('myApp', ['ngRoute'])
  .config(function($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'home.html',
        controller: 'HomeController'
      })
      .when('/about', {
        templateUrl: 'about.html',
        controller: 'AboutController'
      })
      .otherwise({
        redirectTo: '/'
      });
  });
        

In this example:

  • .when('/path', {...}) defines a route for a specific URL path.
  • templateUrl specifies the HTML template to load for the route.
  • controller specifies the controller to associate with the route.
  • .otherwise({redirectTo: '/path'}) defines a fallback route if no other routes match.

The ng-view directive is used in your HTML to render the template associated with the current route.

43. What is ui-router and how does it differ from ngRoute?

ui-router is a third-party routing framework for AngularJS that provides more advanced routing capabilities compared to the built-in ngRoute module. It introduces the concept of states, which allows for nested views and more complex application structures.

Key differences between ui-router and ngRoute:

  • State-Based Routing: ui-router uses states instead of simple URL paths. States can have nested states, enabling complex UI compositions.
  • Nested Views: ui-router supports multiple named views within a single page, allowing for more flexible and dynamic layouts.
  • State Parameters: ui-router allows you to pass parameters to states, making it easier to manage dynamic data.
  • Event System: ui-router provides a robust event system for handling state transitions, such as $stateChangeStart and $stateChangeSuccess.

ui-router is generally preferred for larger and more complex applications due to its flexibility and powerful features.

44. Explain modules in AngularJS.

In AngularJS, a module is a container for different parts of your application, such as controllers, services, directives, and filters. Modules help organize your code into reusable and maintainable blocks. They also manage the dependencies of your application, ensuring that all required components are loaded and available.

A module is created using the angular.module method. You can specify the module’s name and its dependencies as an array of other modules.


var myApp = angular.module('myApp', ['ngRoute', 'ngAnimate']);
        

In this example, myApp is a module that depends on the ngRoute and ngAnimate modules.

Modules are a fundamental part of AngularJS applications, providing a structured way to organize and manage your code.

45. How do you bootstrap an AngularJS application?

Bootstrapping an AngularJS application is the process of initializing and starting the application. There are two ways to bootstrap an AngularJS application: automatically and manually.

Automatic Bootstrapping: This is the most common method. You add the ng-app directive to the root HTML element of your application, typically the <html> or <body> tag. AngularJS automatically initializes the application when the page loads.





  My AngularJS App


  


        

In this example, ng-app="myApp" tells AngularJS to bootstrap the application with the module named myApp.

46. What is manual bootstrapping?

Manual bootstrapping is an alternative method to initialize an AngularJS application. Instead of using the ng-app directive, you manually trigger the bootstrapping process using JavaScript. This method is useful when you need more control over the initialization process, such as when you want to perform some operations before AngularJS starts.

To manually bootstrap an AngularJS application, you use the angular.bootstrap method.


angular.element(document).ready(function() {
  angular.bootstrap(document, ['myApp']);
});
        

In this example, the application with the module myApp is manually bootstrapped when the document is ready.

47. What are AngularJS expressions?

AngularJS expressions are JavaScript-like code snippets that are evaluated within the AngularJS context. They are typically used in HTML templates to bind data to the view. Expressions are written inside double curly braces {{ }} and are evaluated by AngularJS to produce a result.

Expressions can contain literals, operators, and variables. They are a powerful feature for dynamically displaying data in your templates.


{{ 5 + 5 }}

{{ user.name }}

In this example, the first expression evaluates to 10, and the second expression displays the value of the user.name property.

48. How do AngularJS expressions differ from JavaScript expressions?

While AngularJS expressions and JavaScript expressions share similarities, there are some key differences:

  • Context: AngularJS expressions are evaluated within the AngularJS context, which means they have access to the scope and its properties. JavaScript expressions, on the other hand, are evaluated within the global window context.
  • Forgiving: AngularJS expressions are more forgiving than JavaScript expressions. For example, trying to access a property of null or undefined in an AngularJS expression does not throw an error, whereas it would in JavaScript.
  • No Control Flow Statements: AngularJS expressions do not support control flow statements like if, for, or while. Instead, you use directives like ng-if and ng-repeat for control flow.
  • Filters: AngularJS expressions support filters, which allow you to format and transform data directly in the template.

AngularJS expressions are designed to be simple and safe to use in templates, making them ideal for data binding.

49. What is ng-app directive?

The ng-app directive is used to define the root element of an AngularJS application. It automatically initializes or bootstraps the application when the page loads. The ng-app directive is typically placed on the <html> or <body> tag.

You can specify the name of the AngularJS module that should be used to bootstrap the application.





  My AngularJS App


  


        

In this example, ng-app="myApp" tells AngularJS to use the module named myApp to bootstrap the application.

50. What is ng-init directive?

The ng-init directive in AngularJS is used to initialize application data directly in the HTML template. It allows you to set initial values for variables that can be used within the scope of the element where it is defined.

While ng-init can be useful for quick prototyping or simple initialization, it is generally recommended to initialize data in a controller for better maintainability.


Hello, {{ name }}!

In this example, the ng-init directive initializes the name variable to 'John', which is then displayed in the paragraph.

51. What is ng-model directive?

The ng-model directive in AngularJS is used to bind the value of HTML form elements (like input, select, and textarea) to application data. It creates a two-way data binding between the view and the model, meaning any changes in the view are automatically reflected in the model, and vice versa.

This directive is essential for handling user input and keeping the model up-to-date without manual DOM manipulation.



Hello, {{ user.name }}!

In this example, typing in the input field updates the user.name property, and the paragraph displays the updated value in real-time.

52. What is ng-bind directive?

The ng-bind directive in AngularJS is used to bind application data to the HTML view. It replaces the content of an HTML element with the value of a given expression. Unlike interpolation ({{ expression }}), ng-bind is not visible to the user until the data is loaded, which helps prevent the “flicker” effect where raw template markings are briefly visible.


Here, the content of the paragraph will be replaced with the value of user.name.

53. What is ng-repeat directive?

The ng-repeat directive is used to iterate over a collection (like an array or an object) and generate HTML elements for each item in the collection. It is commonly used to display lists of data.


  • {{ item.name }}

In this example, ng-repeat iterates over the items array, creating a list item for each object in the array and displaying its name property.

54. How does ng-repeat handle duplicates with track by?

The track by expression in ng-repeat is used to optimize performance and handle duplicate items in a collection. By default, AngularJS associates each item in the collection with its position in the array. If the collection contains duplicate items, AngularJS may throw an error. Using track by allows you to specify a unique identifier for each item, such as an id property.


  • {{ item.name }}

In this example, track by item.id ensures that AngularJS tracks items by their id property instead of their position, preventing errors with duplicate items.

55. What is ng-show and ng-hide?

The ng-show and ng-hide directives in AngularJS are used to conditionally show or hide HTML elements based on an expression. If the expression evaluates to true, ng-show displays the element, while ng-hide hides it. These directives use CSS to toggle the visibility of elements.


This is visible when isVisible is true.

This is hidden when isVisible is true.

In this example, the first paragraph is visible when isVisible is true, and the second paragraph is hidden when isVisible is true.

56. What is ng-if directive?

The ng-if directive in AngularJS is used to conditionally include or exclude an HTML element from the DOM based on an expression. If the expression evaluates to false, the element is removed from the DOM. This is different from ng-show and ng-hide, which only toggle the visibility of elements using CSS.


This is only in the DOM when isVisible is true.

Here, the paragraph is only included in the DOM when isVisible is true.

57. What is ng-switch directive?

The ng-switch directive in AngularJS is used to conditionally display one of several possible HTML elements based on the value of an expression. It is similar to a switch statement in JavaScript.


Admin View
User View
Guest View

In this example, the content displayed depends on the value of user.role. If user.role is "admin", the “Admin View” is shown. If it is "user", the “User View” is shown. Otherwise, the “Guest View” is displayed.

58. What is ng-click directive?

The ng-click directive in AngularJS is used to specify custom behavior when an element is clicked. It allows you to call a function or evaluate an expression when the click event occurs.



        

In this example, clicking the button calls the greet() function defined in the controller.

59. What is ng-disabled directive?

The ng-disabled directive in AngularJS is used to dynamically enable or disable an HTML element, such as a button or input field, based on an expression. If the expression evaluates to true, the element is disabled.



        

Here, the button is disabled when isDisabled is true.

60. Explain form validation in AngularJS.

AngularJS provides built-in support for form validation through directives and CSS classes. It allows you to validate user input in forms and display appropriate error messages. AngularJS tracks the state of form controls (like input, select, and textarea) and updates their validity status in real-time.

Key features of form validation in AngularJS:

  • Directives: AngularJS provides validation directives like required, ng-minlength, ng-maxlength, and ng-pattern to enforce validation rules.
  • CSS Classes: AngularJS automatically adds CSS classes to form elements based on their validation state, such as ng-valid, ng-invalid, ng-pristine, and ng-dirty.
  • Form Controller: Each form in AngularJS has a form controller that keeps track of the validation state of all its child controls.

Username is required. Username must be at least 3 characters long.

In this example, the form validates that the username field is required and has a minimum length of 3 characters. Error messages are displayed if the validation fails.

91. What is the role of ng-template?

The ng-template directive in AngularJS is used to define a template that can be reused across your application. It allows you to declare a template in your HTML and reference it by its ID in other directives like ng-include or in routing configurations. This is particularly useful for creating reusable UI components or layouts.



        

In this example, the template with the ID myTemplate can be included in other parts of the application using ng-include or referenced in routing.

92. What is content projection or transclude?

Content projection or transclusion in AngularJS refers to the process of including and displaying the content of a directive’s element in a specific location within the directive’s template. This allows you to create reusable components that can wrap arbitrary content provided by the user.

Transclusion is enabled by setting the transclude property to true in the directive definition object. The transcluded content is then inserted into the directive’s template using the ng-transclude directive.


angular.module('myApp').directive('myDirective', function() {
  return {
    transclude: true,
    template: '
This is a directive:
' }; });

In this example, any content inside the <my-directive> element will be inserted where the <ng-transclude> directive is placed.

93. Explain the difference between ng-transclude and ng-content (in context of AngularJS).

In AngularJS, ng-transclude is used for transclusion, which is the process of including the content of a directive’s element in its template. However, ng-content is not a directive in AngularJS; it is a feature in Angular (the successor to AngularJS). In AngularJS, transclusion is achieved solely through ng-transclude.

ng-transclude is a directive that marks the point in the template where the transcluded content should be inserted. It is used within the directive’s template to include the content from the directive’s element.



  

This content will be transcluded.


angular.module('myApp').directive('myDirective', function() {
  return {
    transclude: true,
    template: '
' }; });

94. How to communicate between controllers?

In AngularJS, communication between controllers can be achieved through several methods:

  • Services: Create a shared service to hold data and methods that can be accessed by multiple controllers.
    
    angular.module('myApp').service('sharedService', function() {
      var message = '';
      return {
        getMessage: function() {
          return message;
        },
        setMessage: function(newMessage) {
          message = newMessage;
        }
      };
    });
                    
  • Events: Use $emit, $broadcast, and $on to communicate between controllers through events.
    
    $scope.$emit('myEvent', { data: 'Some data' });
    $scope.$on('myEvent', function(event, data) {
      console.log('Event received:', data);
    });
                    
  • $rootScope: Use the $rootScope to share data globally across controllers.
    
    angular.module('myApp').run(function($rootScope) {
      $rootScope.sharedData = 'Hello, World!';
    });
                    
  • Controller Inheritance: Use nested controllers and prototype inheritance to share data between parent and child controllers.

95. What are best practices for organizing AngularJS code?

Organizing AngularJS code effectively is crucial for maintaining scalability and readability. Here are some best practices:

  • Modularization: Divide your application into logical modules based on features or functionality.
  • Directory Structure: Use a consistent directory structure to separate controllers, services, directives, and views.
    my-app/
    ├── app.js
    ├── controllers/
    │   └── myController.js
    ├── services/
    │   └── myService.js
    ├── directives/
    │   └── myDirective.js
    └── views/
        └── myView.html
                    
  • Dependency Injection: Use dependency injection to manage dependencies and make your code more testable.
  • ControllerAs Syntax: Prefer the controllerAs syntax over $scope for better readability and to avoid scope-related issues.
  • Services for Business Logic: Move business logic and data manipulation to services rather than keeping it in controllers.
  • Minimize Watchers: Reduce the number of watchers to improve performance, especially in large applications.
  • Use Directives for Reusable Components: Encapsulate reusable UI components and behavior in directives.
  • Testing: Write unit tests and end-to-end tests to ensure the reliability of your code.

96. Explain the use of $parse service.

The $parse service in AngularJS is used to convert AngularJS expressions into functions. This allows you to evaluate expressions in the context of a specific scope. The $parse service is particularly useful for dynamically evaluating expressions, such as those provided by users or stored in variables.


angular.module('myApp').controller('MyController', function($scope, $parse) {
  var getter = $parse('user.name');
  var setter = getter.assign;
  var context = { user: { name: 'John' } };

  console.log(getter(context)); // Outputs: John
  setter(context, 'Jane');
  console.log(getter(context)); // Outputs: Jane
});
        

In this example, the $parse service is used to create a getter and setter for the expression user.name.

97. What is $compile service?

The $compile service in AngularJS is used to compile HTML strings or DOM elements into template functions. This process attaches directives and scope bindings to the HTML, making it interactive. The $compile service is a core part of AngularJS’s templating system and is typically used when you need to dynamically add or manipulate DOM elements.


angular.module('myApp').controller('MyController', function($scope, $compile) {
  var html = '
{{ user.name }}
'; var element = $compile(html)($scope); angular.element(document.body).append(element); });

In this example, the $compile service compiles an HTML string and appends it to the document body.

98. How to debug AngularJS applications?

Debugging AngularJS applications can be done using several tools and techniques:

  • Browser Developer Tools: Use the browser’s developer tools to inspect elements, network requests, and JavaScript execution.
  • AngularJS Batarang: A Chrome extension that provides tools for debugging and profiling AngularJS applications.
  • Console Logging: Use console.log to output debugging information to the browser’s console.
  • $log Service: AngularJS provides a $log service for logging messages.
    
    angular.module('myApp').controller('MyController', function($log) {
      $log.info('Controller initialized');
    });
                    
  • Breakpoints: Use the browser’s debugger to set breakpoints in your JavaScript code.
  • Error Handling: Implement global error handling to catch and log errors.

99. What is Batarang tool?

Batarang is a Chrome extension designed to debug and profile AngularJS applications. It provides a set of tools that allow developers to inspect the scope hierarchy, performance, and dependencies of an AngularJS application. Batarang helps visualize the application’s structure and identify performance bottlenecks.

Key features of Batarang include:

  • Scope inspection
  • Performance profiling
  • Dependency visualization
  • Model browser

Batarang is a valuable tool for developers working with AngularJS, making it easier to debug and optimize applications.

100. Why is AngularJS still used in legacy applications in 2026?

AngularJS is still used in legacy applications in 2026 for several reasons:

  • Stability: Many legacy applications built with AngularJS are stable and meet the business requirements. Migrating to a newer framework can be costly and time-consuming.
  • Cost of Migration: Migrating a large application from AngularJS to a newer framework like Angular or React involves significant effort, testing, and potential downtime.
  • Long-Term Support: Although AngularJS reached its end of life, many organizations continue to maintain and update their existing AngularJS applications with community support and internal resources.
  • Familiarity: Development teams may be more familiar with AngularJS, making it easier to maintain and extend existing applications.
  • Functionality: AngularJS provides all the necessary features for many applications, and the need for new features may not justify a migration.
  • Integration: Legacy systems often have complex integrations with other systems, making migration challenging.

While newer frameworks offer advanced features and performance improvements, the practical considerations of migration often lead organizations to continue using AngularJS for their legacy applications.

Latest Post

Share:
Previous: 100 Top Python Interview Questions
Next: 150 Top-Asked Agile & Scrum Interview Questions in 2026
150 Top-Asked Agile & Scrum Interview Questions in 2026

150 Top-Asked Agile & Scrum Interview Questions in 2026

Having spent over a decade coaching teams through Agile transformations, I’ve watched the landscape evolve from niche methodology to near-universal…

By Question Mentor
NewADO.NET Interview Questions and Answers

200 ADO.NET Interview Questions and Answers for 2026

As we enter 2026, ADO.NET remains a critical skill in the .NET landscape, not as a legacy relic, but as…

By Question Mentor
New100 Docker Interview Questions and Answers

100 Docker Interview Questions and Answers

100 Docker Interview Questions and Answers for 2026 1. What is Docker? Docker is an open-source platform designed to automate…

By Question Mentor
FEEDBACK