AngularJS Interview Questions

  1. List some of the built-in validators in AngularJS ?
  2. List some tools for testing AngularJS applications?
  3. Explain the architecture of AngularJS ?
  4. What is dependency injection In AngularJs and how does it work?
  5. Explain UI Routing in AngularJS ?
  6. List some difference between AngularJS and Angular 2?
  7. How to create a service using Factory in AngularJS ?
  8. How to hide or show a div in AngularJS ?
  9. Explain ng-include directive in AngularJS ?
  10. How to disable a control or element in AngularJS ?
  11. How to create a service in AngularJS ?
  12. Explain Event in AngularJS , List some events you have worked in AngularJs?
  13. What is different between ng routing and UI routing in AngularJS ?
  14. What is a dynamic route in AngularJS and how do you implement it?
AngularJS Interview Questions

AngularJS is an open source model view controller MVC JavaScript framework that is used for making rich, extensible web applications. It runs on plain JavaScript and HTML, so you don't need any other dependencies to make it work.

Below are some basic facts about AngularJS that must an AngularJs Developer know before appearing in AngularJs Interview

  • Based On: MVC and MVVM design pattern. Design Patterns in programming languages are used to write reusable and maintainable code for commonly occurring problems in Software Engineering.
  • Written In: AngularJs 1.x is written in Javascript. It one of the most popular programming language on the web for creating interactive and scalable front end and server applications.
  • Supported Features: AngularJS supports features like bundling codes in modules, Dependency Injection, Routing, two-way data binding, services that help developers to write clean and reactive, user-friendly applications using Javascript.
  • Best Suited for: AngularJs is best suited for creating Single Page Applications and admin backends
  • Maintained By: It is maintained by Google Inc.
  • Licensed: Angular JS is licensed under MIT License that means anyone can modify the source code and republish it.

Best Angular Js Interview Questions and answers

Download AngularJS Interview Questions PDF

Angular js supports all standard HTML5 attributes to validate input. Below are few built-in validators in Angular js.

  • required
  • min
  • max
  • type=”number” OR type=”email”

For testing AngularJS applications there are certain tools that you should use that will make testing much easier to set up and run.

Karma

Karma is a JavaScript command line tool that can be used to spawn a web server which loads your application’s source code and executes your tests. You can configure Karma to run against a number of browsers, which is useful for being confident that your application works on all browsers you need to support. Karma is executed on the command line and will display the results of your tests on the command line once they have run in the browser.

Karma is a NodeJS application and should be installed through NPM/YARN. Full installation instructions are available on the Karma website.

Jasmine

Jasmine is a behavior-driven development framework for JavaScript that has become the most popular choice for testing AngularJS applications. Jasmine provides functions to help with structuring your tests and also making assertions. As your tests grow, keeping them well structured and documented is vital, and Jasmine helps achieve this.

Jasmine comes with a number of matches that help you make a variety of assertions. You should read the Jasmine documentation to see what they are. To use Jasmine with Karma, we use the karma-jasmine test runner.

angular-mocks

AngularJS also provides the ngMock module, which provides mocking for your tests. This is used to inject and mock AngularJS services within unit tests. In addition, it is able to extend other modules so they are synchronous. Having tests synchronous keeps them much cleaner and easier to work with. One of the most useful parts of ngMock is $httpBackend, which lets us mock XHR requests in tests and return sample data instead.

Source:https://docs.angularjs.org/guide/unit-testing

AngularJS is architecture on 3 components. They are

  • The Template (View)
  • The Scope (Model)
  • The Controller (Controller)

AngularJS extends HTML attributes with Directives and binds data to HTML with Expressions.

AngularJS was designed to highlight the power of dependency injection, a software design pattern that places an emphasis on giving components of their dependencies instead of hardcoding them within the component. For example, if you had a controller that needed to access a list of customers, you would store the actual list of customers in a service that can be injected into the controller instead of hardcoding the list of customers into the code of the controller itself. In AngularJS you can inject values, factories, services, providers, and constants.

It is a routing framework for AngularJS and provides a different approach than ngRoute. It changes the application views based on the state of the application and not just the route URL

Difference between AngularJS and Angular 2

AngularJSAngular 2
Angular js or Angular 1.x is based on MVC ArchitectureAngular 2 is based on service/ components
Javascript is used to write applications in Angular js.Typescript (a superset of javascript) is used to write an application in Angular2.
A controller is used to writing logic and interact with Model and view.In Angular 2 Controllers are totally eliminated and Components take its place.
Angular 1 is created for developing Single page web-applications.In Angular 2 can be used for developing native applications for a mobile platform like React Native as well as interactive
web applications.
Angularjs is easy to set up, you just need to include the angular.js library to start.Angular 2 is dependent on other modules/ package. It gives little brainstorm to install and run Angular 2.
In Angularjs ng-app directive is used bootstrap the app.ng-app is removed in Angular 2. You need to call Angular2 bootstrap method to bootstrap your application.

Creating a service using the module's factory API is one of the most common ways to create a service. We first create an object, add properties to it and return the same object, which can later be injected into the components like service, controller, filter or directive.

In order to hide/show the div in AngularJS just get rid of display: none, the rest is in the control. If you want to hide it by default then set the value of scope.myvalue to false.

The HTML pages can be embedded within an HTML page using the ng-include directive.

Using ng-disabled attribute will help you disable element in AngularJS.

The service in AngularJS is created by registering it with the module it is going to operate in. There are three ways to create the angular service. They are:

  • Factory
  • Service
  • Provider

The AngularJS framework includes certain directives that can be used to provide the custom behavior on various DOM events. Some of the events are:

  • ng-click
  • ng-keyup
  • ng-keydown
  • ng-keypress
  • ng-dblclick
  • ng-mousedown
  • ng-mouseleave
  • ng-mouseenter
  • ng-change

The ng routing is deep linking services and directives for angular applications whereas the UI routing is a 3rd party module routing and is very powerful. It does everything an ng router does as well as has many other extra functions.

A dynamic route is a typical approach to server communication is using the HTTP server. In order to implement it, firstly write a config function that uses $http and $routeprovider to gather all information on available routes.

The different types of directives available in AngularJS are:

  • Element directives − It activates when a matching element is encountered.
  • Attribute − It activates when a matching attribute is encountered.
  • CSS − It activates when a matching CSS style is encountered.
  • Comment − It activates when a matching comment is encountered.

AngularJS is a framework with key features like models, two-way binding, directives, routing, dependency injections, unit tests etc., whereas the Jquery is a library used for DOM manipulation with no two-way binding features.

The provider in AngularJS is used to internally create a factory, services etc., during the phase of configuration. The provider is the special factory method which is used to return the service/value/factory.

In order to disable the right click event in AngularJS, you need to add the disable-right-click as the element’s attribute. Simply use preventDefault(), this cancels the event and stops further propagation of the event.

$evalAsync executes the expression on the current scope at a later time and makes no guarantees as to when the expression will be executed.

$timeout also executes the expression on the current scope on later time but also runs after the DOM has been manipulated by the Angular and after the browser renders that cause flicker in some cases.

It is a scope that exists separately with no prototypal inheritance. It makes the components reusable and permits to control the binding either one-way or two-way.

Scopeless controllers have no $scope injected and the functions and properties are binded directly onto the controller. Scopeless controllers are used in the situation where the controller becomes complex by using the $scope to provide data.

The AngularJS provides a date filter through which you can format the date into the required form.

Syntax

{{ today | date:'MM/dd/yyyy'}}

To animate the application, you need to include the AngularJS Animate Library and then refer to the ngAnimate module into the application or add ngAnimate as a dependency in your application module.

It is used to prevent the Angular HTML template from getting displayed briefly by the browser in its uncompiled form while the application is still loading. It is used to avoid the undesirable flicker effect caused by HTML template display.

$Location is used when you don't want the full page to reload when the URL is changed and the window.location is used when you want to change the URL, reload the page or navigate to a different page.

The $scope is an object with the available methods and properties. It is used to get all controls on the controller.JS files. It is available for both the controller and the view. "This" is the controller used when the controller’s constructor function is called.

The $http.post method is used to send an http post request in AngularJS. The method has three parameters namely URL, data, config.

Define a directive, use that directive on the element we are targeting and have it $watch a trigger/property to know when to focus the element.

There are two ways to use a Multiple ng-app within a single page in AngularJS. One is the bootstrap method and the other is ngModules directive.

It is used to allocating the value of an object into another object however the object value must not be altered.

If you are adding any new property or altering any value of the property then the object noting to the same object will update by applying angular. Copy() method.

In AngularJS $scope.$watch the function is used to create a watch of some variables and $scope.$apply function is used to execute some code and call the $digest function.

Here is the list of cons of AngularJS

    • JavaScript support mandatory

Just be imagine, the devices that access your server but they are disabled for JavaScript. So the users are unable to access into your web apps or website. In the case of a great number of users, AngularJS based web is not so efficient. In spite of this, it is good for plain HTML-based web.

    • Greenness with Model View Controller (MVC)

If you are a developer and wants to do some traditional with almost zilch knowledge of MVC then you are not advised to use the Angular.JS because it will be time-consuming for you. You should hire an expert who has good knowledge of MVC if you are short in time to submit the project

    • The dilemma scopes

If you are fresh in Angular.JS then it will be difficult for you to deal with complex entities such as Quite layered and hierarchically and scopes. Debugging the scope is a believed a very hard task for many programmers.

    • Other difficult features

There are several features of Angular.JS like directives, dependency injection and factories which are hard to use. So, you have to spend a lot of time on it to understand all of them or prefer to hire an expert.

    • Time consumption in old devices

The browser on old computer and mobile are failed or take a little more time to render pages of application and websites designed using the framework. It happens because the browser begins to complete some supplementary tasks like DOM manipulation. But this quibble does not seem in the new devices.

    • Difficult to learn

It is very hard to accustom to the framework. Plus, you may get some additional problems like limited documentation. But Angular.JS continuously make it easier

Compile – It compiles an HTML DOM into a template and produces a template function that is used to link scope and template together. It is executed only once.

Pre-link – It is executed before the child elements are linked.

Post-link – It is executed after the child elements are linked.

The caching is implemented by using a cache object that stores and retrieves data and is primarily used by $templaterequest and script directive to cache the templates.

It is the most common type of dependency on AngularJS application. A service can be mocked in two ways by either getting an instance of actual service using an inject block or by implementing a mock service using $provide.

Angualr.JS filters are efficient in modifying the data. With the help of pipe (|) character, they are clubbed into the directive or expression.

FiltersFunctions
UppercaseIt used to convert text to upper case text.
LowercaseIt used to convert text to lower case text.
CurrencyIt is used to formats a number to a currency format.
Order byIt is used to orders the array on the basis of given criteria.
FilterIt is used to order the array to a subset of it on the basis of given criteria.

.config() – The .config() function is used to add configuration blocks on the module.

.run() - The .run() function is used to add run blocks on the module.

AngularJS provides full support for both the unit and end-to-end testing.

The unit testing is a method that helps the developers validate the isolated pieces of code and end-to-end testing is required when you want to ascertain the set of components integrated together work as you expect.

$templateCache is a Cache object that is created by the $cache factory. The first time you use a template, it is loaded in the $templateCache for easy and quick retrieval.

The track by is used with ng-repeat and describes to AngularJS how it tracks the association between the DOM and the Model. It improves the rendering performance.

Some of the methods supported by $http services are

  • GET
  • HEAD
  • POST
  • PUT
  • DELETE
  • CONNECT
  • OPTIONS
  • TRACE

A stateful component is a detail implementation of the component that can change over time and the stateful components can have stateless components inside them, while the stateless components are a plain JavaScript function.

A locale is a particular geographical region. The commonly used locale ID comprises of two parts, the language code, and the country code.

An interceptor is a middleware code in AngularJs where all the $http requests go through. It is attached with $httpProvider service and able to intercept request and response objects. Interceptor Middleware is useful for error handling, authentication and other filters you want to apply on request and response.

DDO Stands for Directive Definition Object. DDO is used while creating a custom directive in AngularJs.

Angular uses these prefixes to prevent accidental code collision with users code.
$ prefix is used with public objects whereas $$ prefix is used with a private object.

$broadcast, $emit, and $on are services in Angular Js. Below we have listed why they are used In Angular JS.

$broadcast(): $broadcast() service of Angular is used to propagate the event to all of his child controllers and it’s registered parent $rootscope.scope listeners.

$rootScope.$broadcast('SummaryEvent', {
                priority: priority               
      });

$on(): AngularJS $on() service is used to listen any type of event raised by $broadcast and $emit.

$scope.$on(''SummaryEvent'', function (event, args) {
Vm.priority=args.priority
   });

$emit: $emit is similar to $broadcast service but it is used to propagate the event to upwards through the scope hierarchy and notify to the registered $rootScope.Scope listeners.

Routing is one the core feature of AngularJs Framework that is useful in building a single page web application with multiple views. In Angular ngRoute Module is used to implement Routing. ngView,$routeProvider,$route and $routeParams are different components of the ngRoute Module that helps to configure and mapping Url to views.

There are 30 inbuilt services in AngularJs. Below are few most used services in AngularJs.

  • $location
  • $scope
  • $http
  • $timeout
  • $interval
  • $window

The transclusion in Angular JS will allow you to move the original children of a directive to a specific location inside a new template.The ng directive marks the insertion point for the transcluded DOM of the very near parent directive that uses transclusion.
ng-transclude or ng-transclude-slot attribute directives are used for transclusion in Angular JS.

locale service provides with the localization rules for Angular JS components.

Adding the regex directly to the ng pattern to the attribute can help you validate the URL in Angular JS.

Passing the $interpolateprovider in the config can help us change the start and end symbols used in our Angular JS expressions.

ng-if – This directive removes a portion of the DOM tree, which is based on the expression.
In case the expression is assigned to ng-if, it evaluates to a false value, and then the element is deleted from the DOM tree, or else a clone of the element is reinserted into the DOM.
ng-switch – This directive is used based on a scope expression to conditionally swap DOM structure on the template.
The ng-switch default directive will be preserved at the specific location in a template.
ng-repeat – This directive is used to instantiate the template once per item from a collection.
Each template which is instantiated gets its own scope where the given loop variable is set to the current collection of item.

Caching can be enabled by setting the config.cache value or the default cache value to TRUE or to a cache object that is created with $cacheFactory.
In case you want to cache all the responses, then you can set the default cache value to TRUE.
And, if you want to cache a specific response, then you can set the config.cache value to TRUE.

The RouteProvider and the RouteParams can be used to get the URL parameters in the controller.
As the route wires up the URL to the controller and RouteParams can be passed to the controller to get the URL parameters.

Compile function: To template DOM manipulation and to gather all the directives, the compile function is used.
Link function: To register DOM listeners as well as for the instance DOM manipulation, the Link function is used.

Angular form validation and ng-pattern directive can be used to validate the email and phone number in Angular JS.

In angular there is a scope variable called $parent (i.e. $scope.$parent). $parent is used to access parent scope from child controller in Angular JS.
Example:


<div ng-controller="ParentCtrl">
    <h1>{{ name }}</h1>
    <p>{{ address }}</p>
    <div ng-controller="ChildCtrl">
        <h1>{{ title }}</h1>
        <input type="text" ng-model="$parent.address" />
</div>

In angular Directives are used to extend the attributes of Html elements.
Creating custom directive in Angular js.
Angular js Directives are restricted to element and attribute and created using a directive function.Here is sample code to create a directive in Angular js.


var app = angular.module("myApp", []);
app.controller('AppController', function($scope) {
    var users=[];
    var user1={};
    user1.firstName="Satyam";
    user1.lastName="Kumar";
    users.push(user1);
    var user2={};
    user2.firstName="Ravi";
    user2.lastName="Sankar";
    user2.push(user2);
    $scope.users=students;
});
app.directive('user', function() {
    //define the directive object
    var directive = {};
    //restrict = E, implies that directive is Element directive
    directive.restrict = 'E';
    //element will be replaced by this text/html
    directive.template = "First Name: {{user.firstName}} , Last Name: {{user.lastName}}";
    var linkFunction = function($scope, element, attributes) {
        element.css("background-color", "#e1e1e1");
    }
    directive.link=linkFunction;
    return directive;
});

As Above directive is restricted to Element directive, so you can use this directive as an element only.
Usage:


<div ng-app="app">
 <h1>Custom Directive Demo</h1>
 <div ng-controller="UserController">
 <div ng-repeat="user in users">
 <user></user>
 </div>
 </div>
</div>

html5Mode method of $locationProvider module is used to enable HTML5 mode in Angular 1.x. For creating pretty URLs and removing # from URLs html5Mode need to true.

Enabling html5Mode to true in Angular 1.x.


angular.module('myApp', [])

    .config(function($routeProvider, $locationProvider) {

        $routeProvider
            .when('/', {
                templateUrl : 'partials/home.html',
                controller : mainController
            })
            

        // use the HTML5 History API
        $locationProvider.html5Mode(true);
    });

Below are some major browsers supported by Angular js

  • Mozilla Firefox
  • Google Chrome
  • Microsft Edge
  • IE 10,11
  • IE Mobile,
  • Safari, iOS
  • Android: Nougat (7.0) Marshmallow (6.0)

Angular js Expression is JavaScript alike code snippets used to bind expression data in view or HTML. Angular expressions are written inside two curly braces.

{{a+b}}

In Angular js $scope is used whenever we have to use dependency injection (D.I) whereas as the scope is used for directive linking.

In Angular JS $rootscope and $scope both are an object which is used for sharing data from the controller to view.
The main difference between $rootscope and $scope is that $rootscope is available globally to across all the controllers whereas $scope is available only in controllers that have created it along with its children controllers.

Data-binding in Angular apps is the automatic synchronization of data between the model and view components. The way that Angular implements data-binding lets you treat the model as the single-source-of-truth in your application. The view is a projection of the model at all times. When the model changes, the view reflects the change and vice versa.

The $routeProvider is used to configure roots within an AngularJS application. It can be used to link a URL with a corresponding HTML page or template, and a controller (if applicable).

To add promise functionality to a service, we inject the “$q” dependency in the service, and then use it like so:


angular.factory('testService', function($q){
return {
getName: function(){
var deferred = $q.defer();

//API call here that returns data
testAPI.getName().then(function(name){
deferred.resolve(name)
})

return deferred.promise;
}
}
})

The $q library is a helper provider that implements promises and deferred objects to enable asynchronous functionality

Source: https://docs.angularjs.org/api/ng/service/$q

In One-Way data binding, view (UI part) not updates automatically when data model changed. We need to write custom code to make it updated every time.
ng-bind has one-way data binding.

While in two way binding scope variable will change it’s value every time its data model changed is assigned to a different value.

You can isolate a directive’s Scope by passing an object to the scope option of directive.
This tells the directive to keep scope inside of itself and not to inherit or share with other scopes.

There are three types of directive scopes available in Angular.

  • Parent Scope: is default scope
  • Child Scope:  If the properties and functions you set on the scope are not relevant to other directives and the parent, you should probably create a new child scope.
  • Isolated Scope: Isolated Scope is used if the directive you are going to build is self-contained and reusable. Does not inherit from parent scope, used for private/internal use.

Angular Modules are place where we write code of our Angular application.Writing Modules makes our code more maintainable, testable, and readable. All dependencies for our app are defined in modules.

Below are some major difference between AngularJS and JavaScript Expressions

  • Both can contain literals, operators, and variables.
  • AngularJS expressions can be written in HTML but JavaScript expressions are not.
  • AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do.
  • AngularJS expressions support filters, while JavaScript expressions do not.

Internationalization is a way to show locale-specific information on a website.It is used to create multilingual language websites.

AngularJS digest cycle is the process behind Angular JS data binding.
In each digest cycle, Angular compares the old and the new version of the scope model values. The digest cycle is triggered automatically. We can also use $apply() if we want to trigger the digest cycle manually.

We can share data by creating a service, Services are easiest, fastest and cleaner way to share data between controllers in AngularJs.
There are also other ways to share data between controllers, they are

  • Using Events
  • $parent, nextSibling, controllerAs
  • Using the $rootScope

AngularJS directives are extended HTML attributes with the prefix ng-
The 3 main directives of angular js are

  • ng-app:- directive is used to flag the HTML element that Angular should consider to be the root element of our application. Angular uses spinal-case for its custom attributes and camelCase for the corresponding directives which implement them.
  • ng-model:- directive allows us to bind values of HTML controls (input, select, textarea) to application data. When using ngModel, not only change in the scope reflected in the view, but changes in the view are reflected back into the scope.
  • ng-bind:- directive binds application modal data to the HTML view.

The controller is a function which generally takes an empty scope object as a parameter and adds to it the fields and functions that will be later exposed to the user via the view.

The scope is the object that represents the “model” of your application. It contains fields that store data which is presented to the user via the template, as well as functions which can be called when the user performs certain actions such as clicking a button.

The template is the HTML portion of the angular app. It is exactly like a static HTML page, except that templates contain additional syntax which allows data to be injected in it in order to provide a customized user experience.

AngularJS is a JavaScript framework that is used for making rich, extensible web applications. It runs on plain JavaScript and HTML, so you don’t need any other dependencies to make it work.AngularJS is perfect for Single Page Applications (SPA). It is basically used for binding JavaScript objects with HTML UI elements.

  • Create an angular.module
  • Assign a controller to the module
  • Link your module to HTML with ng-app
  • Link the controller to HTML with ng-controller directive