Angular Interview study questions and answers
What is the use of $routeProvider in AngularJS?
$routeProvider is the key service which set the configuration of urls, maps them with the corresponding html page or ng-template, and attaches a controller with the same.
How is angularjs different from other JavaScript frameworks?
1. Angular mark-up lives in the DOM. 2. Angular uses plain JavaScript objects (POJO) 3. Angularjs uses dependency injection
What are the advantages of AngularJS?
1. AngularJS provides capability to create Single Page Application in a very clean and maintainable way. 2. AngularJS provides data binding capability to HTML thus giving user a rich and responsive experience. 3. AngularJS code is unit testable. 4. AngularJS uses dependency injection and make use of separation of concerns. 5. AngularJS provides reusable components. 6. With AngularJS, developer writes less code and gets more functionality. 8. In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing. 9. AngularJS applications can run on all major browsers and smart phones including Android and iOS based phones/tablets.
How to use jquery with Angularjs
1. By default Angularjs uses jQlite, loading jquery before angular will cause Angularjs to use it.
What components can be defined within Angularjs modules?
1. Directive 2. Filter 3. Controller 4. Factory 5. Service 6. Provider 7. Value 8. Config settings and routes
What are reasons to use angular
1. It is based on the MVC pattern 2. It extends html by attaching directives to html 3. It allows you to make your own directives making reusable components that fill your needs and abstracts your DOM manipulation logic 4. It supports two way binding i.e connects your HTML views to your JavaScript objects (models) seamlessly. 5. it encapsulates the behavior of your application in controllers which are instantiated with the help of dependency injection. 6. It supports services that can be injected into your controllers for utility purposes 7. It supports dependency injection which helps you to test your code
Does Angularjs have dependency on jquery?
1.No
What are the services in AngularJS?
AngularJS come with several built-in services. For example $http service is used to make XMLHttpRequests (Ajax calls). Services are singleton objects which are instantiated only once in app.
How to validate in AngularJS
AngularJS enriches form filling and validation. We can use $dirty and $invalid flags to do the validations in seamless way. Use novalidate with a form declaration to disable any browser specific validation. Following can be used to track error. $dirty − states that value has been changed. $invalid − states that value entered is invalid. $error − states the exact error.
How to make an ajax call using Angular JS
AngularJS provides $http control which works as a service to make ajax call to read data from the server. The server makes a database call to get the desired records. AngularJS needs data in JSON format. Once the data is ready, $http can be used to get the data from server in the following manner: function studentController($scope,$http) { var url = "data.txt"; $http.get(url).success( function(response) { $scope.students = response; }); }
What components can be injected as a dependency in AngularJS?
AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies. 1. value 2. factory 3. service 4. provider 5. constant
On which types of component can we create a custom directive?
AngularJS provides support to create custom directives for following type of elements. 1. Element directives − Directive activates when a matching element is encountered. 2. Attribute − Directive activates when a matching attribute is encountered. 3. CSS − Directive activates when a matching css style is encountered. 4. Comment − Directive activates when a matching comment is encountered.
How do you implement internationalization in AngularJS?
AngularJS supports inbuilt internationalization for three types of filters currency, date and numbers. We only need to incorporate corresponding js according to locale of the country. By default it handles the locale of the browser. For example, to use Danish locale, use following script
What are the ways to communicate between modules of your application using core AngularJS functionality? Name three ways.
Communication can happen: Using services Using events By assigning models on $rootScope Directly between controllers, using $parent, nextSibling, etc Directly between controllers, using ControllerAs, or other forms of inheritence In the community, there are also mentions of less popular methods such as using watches or the URL.
What are the controllers in AngularJS?
Controllers are JavaScript functions that are bound to a particular scope. They are the prime actors in AngularJS framework and carry functions to operate on data and decide which view is to be updated to show the updated model based data.
Explain the currency filter
Currency filter formats text in a currency format. In below example, we've added currency filter to an expression returning number using pipe character. Here we've added currency filter to print fees using currency format. Enter fees: <input type = "text" ng-model = "student.fees"> fees: {{student.fees | currency}}
What is data binding in Angularjs
Data binding is the automatic synchronization of data between model and view components.
What is deep linking in AngularJS?
Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state.
Explain directives in AngularJS.
Directives are markers on DOM elements (such as elements, attributes, css, and more). These can be used to create custom HTML tags that serve as new, custom widgets. AngularJS has built-in directives (ng-bind, ng-model, etc) to perform most of the task that developers have to do.
What are AngularJS expressions?
Expressions are used to bind application data to html. Expressions are written inside double braces like {{ expression}}. Expressions behave in same way as ng-bind directives. AngularJS application expressions are pure JavaScript expressions and outputs the data where they are used.
What are the filters in AngularJS?
Filters select a subset of items from an array and return a new array. Filters are used to show filtered items from a list of items based on defined criteria.
What are the disadvantages of AngularJS?
Following are the disadvantages of AngularJS. Not Secure − Being JavaScript only framework, application written in AngularJS are not safe. Server side authentication and authorization is must to keep an application secure. Not degradable − If your application user disables JavaScript then user will just see the basic page and nothing more.
what are the core directives of Angularjs?
Following are the three core directives of AngularJS. 1. ng-app − This directive defines and links an AngularJS application to HTML. 2. ng-model − This directive binds the values of AngularJS application data to HTML input controls. 3. ng-bind − This directive binds the AngularJS Application data to HTML tags.
How does the digest phase work?
In a nutshell, on every digest cycle all scope models are compared against their previous values. That is dirty checking. If change is detected, the watches set on that model are fired. Then another digest cycle executes, and so on until all models are stable. It is probably important to mention that there is no ".$digest()" polling. That means that every time it is being called deliberately. As long as core directives are used, we don't need to worry, but when external code changes models the digest cycle needs to be called manually. Usually to do that, ".$apply()" or similar is used, and not ".$digest()" directly.
What is internationalization?
Internationalization is a way to show locale specific information on a website. For example, display content of a website in English language in United States and in Danish in France.
What is routing in AngularJS?
It is concept of switching views. AngularJS based controller decides which view to render based on the business logic.
How does interpolation, e.g. "{{ someModel }}", actually work?
It relies on $interpolation, a service which is called by the compiler. It evaluates text and markup which may contain AngularJS expressions. For every interpolated expression, a "watch()" is set. $interpolation returns a function, which has a single argument, "context". By calling that function and providing a scope as context, the expressions are "$parse()"d against that scope.
Explain the lowercase filter.
Lowercase filter converts a text to lower case text. In below example, we've added lowercase filter to an expression using pipe character. Here we've added lowercase filter to print student name in all lowercase letters. Enter first name:<input type = "text" ng-model = "student.firstName"> Enter last name: <input type = "text" ng-model = "student.lastName"> Name in Upper Case: {{student.fullName() | lowercase}}
What is $rootScope?
Scope is a special JavaScript object which plays the role of joining controller with the views. Scope contains the model data. In controllers, model data is accessed via $scope object. $rootScope is the parent of all of the scope variables.
What is scope hierarchy in AngularJS?
Scopes are controllers specific. If we define nested controllers then child controller will inherit the scope of its parent controller. <script> var mainApp = angular.module("mainApp", []); mainApp.controller("shapeController", function($scope) { $scope.message = "In shape controller"; $scope.type = "Shape"; }); mainApp.controller("circleController", function($scope) { $scope.message = "In circle controller"; }); </script> Following are the important points to be considered in above example. We've set values to models in shapeController. We've overridden message in child controller circleController. When "message" is used within module of controller circleController, the overridden message will be used.
What is scope in Angularjs
Scopes are objects that refer to the model. They act as glue between controller and view.
What is a service?
Services are JavaScript functions and are responsible to do specific tasks only. Each service is responsible for a specific task for example, $http is used to make ajax call to get the server data. $route is used to define the routing information and so on. Inbuilt services are always prefixed with $ symbol.
Explain templates in AngularJS.
Templates are the rendered view with information from the controller and model. These can be a single file (like index.html) or multiple views in one page using "partials".
This is a simple test written for Protractor, a slightly modified example from Protractor docs: it('should find an element by text input model', function() { browser.get('/some-url'); var login = element(by.model('username')); login.clear(); login.sendKeys('Jane Doe'); var name = element(by.binding('username')); expect(name.getText()).toEqual('Jane Doe'); // Point A }); Explain if the code is synchronous or asynchronous and how it works.
The code is asynchronous, although it is written in a synchronous manner. What happens under the hood is that all those functions return promises on the control flow. There is even direct access, using "protractor.promise.controlFlow()", and the two methods of the returned object, ".execute()" and ".await()". Other webdriver libraries, such as wd https://github.com/admc/wd, require the direct use of callbacks or promise chains.
The most popular e2e testing tool for AngularJS is Protractor. There are also others which rely on similar mechanisms. Describe how e2e testing of AngularJS applications work.
The e2e tests are executed against a running app, that is a fully initialized system. They most often spawn a browser instance and involve the actual input of commands through the user interface. The written code is evaluated by an automation program, such as a Selenium server (webdriver). That program sends commands to a browser instance, then evaluates the visible results and reports back to the user. The assertions are handled by another library, for Protractor the default is Jasmine. Before Protractor, there was a module called Angular Scenarios, which usually was executed through Karma, and is now deprecated. Should you want to e2e test hybrid apps, you could use another Selenium server, called Appium. Testing can be handled manually, or it can be delegated to continuous integration servers, either custom or ones provided by Travis, SauceLabs, and Codeship.
When a scope is terminated, two similar "destroy" events are fired. What are they used for, and why are there two?
The first one is an AngularJS event, "$destroy", and the second one is a jqLite / jQuery event "$destroy". The first one can be used by AngularJS scopes where they are accessible, such as in controllers or link functions. Consider the two below happening in a directive's postLink function. The AngularJS event: scope.$on('$destroy', function () { // handle the destroy, i.e. clean up. }); And element.on('$destroy', function () { // respectful jQuery plugins already have this handler. // angular.element(document.body).off('someCustomEvent'); }); The jqLite / jQuery event is called whenever a node is removed, which may just happen without scope teardown.
Name and describe the phases of a directive definition function execution, or describe how directives are instantiated.
The flow is as follows: First, the "$compile()" function is executed which returns two link functions, preLink and postLink. That function is executed for every directive, starting from parent, then child, then grandchild. Secondly, two functions are executed for every directive: the controller and the prelink function. The order of execution again starts with the parent element, then child, then grandchild, etc. The last function postLink is executed in the inverse order. That is, it is first executed for grandchild, then child, then parent. A great explanation of how directives are handled in AngularJS is available in the AngularJS Tutorial: Demystifying Custom Directives post on the Toptal blog.
How do you reset a "$timeout", and disable a "$watch()"?
The key to both is assigning the result of the function to a variable. To cleanup the timeout, just ".cancel()" it: var customTimeout = $timeout(function () { // arbitrary code }, 55); $timeout.cancel(customTimeout); The same applies to "$interval()". To disable a watch, just call it. // .$watch() returns a deregistration function that we store to a variable var deregisterWatchFn = $rootScope.$watch('someGloballyAvailableProperty', function (newVal) { if (newVal) { // we invoke that deregistration function, to disable the watch deregisterWatchFn(); ... } });
List a few ways to improve performance in an AngularJS app.
The two officially recommended methods for production are disabling debug data and enabling strict DI mode. The first one can be enabled through the $compileProvider: myApp.config(function ($compileProvider) { $compileProvider.debugInfoEnabled(false); }); That tweak disables appending scope to elements, making scopes inaccessible from the console. The second one can be set as a directive: <html ng-app="myApp" ng-strict-di> The performance gain lies in the fact that the injected modules are annotated explicitly, hence they don't need to be discovered dynamically. You don't need to annotate yourself, just use some automated build tool and library for that. Two other popular ways are: Using one-time binding where possible. Those bindings are set, e.g. in "{{ ::someModel }}" interpolations by prefixing the model with two colons. In such a case, no watch is set and the model is ignored during digest. Making $httpProvider use applyAsync: myApp.config(function ($httpProvider) { $httpProvider.useApplyAsync(true); }); ... which executes nearby digest calls just once, using a zero timeout.
Explain the uppercase filter.
Uppercase filter converts a text to upper case text. In below example, we've added uppercase filter to an expression using pipe character. Here we've added uppercase filter to print student name in all capital letters. Enter first name:<input type = "text" ng-model = "student.firstName"> Enter last name: <input type = "text" ng-model = "student.lastName"> Name in Upper Case: {{student.fullName() | uppercase}}
Explain ng-include directive
Using AngularJS, we can embed HTML pages within a HTML page using ng-include directive. <div ng-app = "" ng-controller = "studentController"> <div ng-include = "'main.htm'"></div> <div ng-include = "'subjects.htm'"></div> </div>
Which means of communication between modules of your application are easily testable?
Using a service is definitely easy to test. Services are injected, and in a test either a real service can be used or it can be mocked. Events can be tested. In unit testing controllers, they usually are instantiated. For testing events on $rootScope, it must be injected into the test. Testing $rootScope against the existence of some arbitrary models is testable, but sharing data through $rootScope is not considered a good practice. For testing direct communication between controllers, the expected results should probably be mocked. Otherwise, controllers would need to be manually instantiated to have the right context.
What is the factory method?
Using factory method, we first define a factory and then assign method to it. var mainApp = angular.module("mainApp", []); mainApp.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b } return factory; });
What is a service method?
Using service method, we define a service and then assign method to it. We've also injected an already available service to it. mainApp.service('CalcService', function(MathService){ this.square = function(a) { return MathService.multiply(a,a); } });
Explain Angular JS boot process.
When the page is loaded in the browser, following things happen: 1. HTML document is loaded into the browser, and evaluated by the browser. AngularJS JavaScript file is loaded; the angular global object is created. Next, JavaScript which registers controller functions is executed. 2. Next AngularJS scans through the HTML to look for AngularJS apps and views. Once view is located, it connects that view to the corresponding controller function. 3. Next, AngularJS executes the controller functions. It then renders the views with data from the model populated by the controller. The page gets ready.
Is AngularJS extensible?
Yes! In AngularJS we can create custom directive to extend AngularJS existing functionalities. Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using "directive" function. A custom directive simply replaces the element for which it is activated. AngularJS application during bootstrap finds the matching elements and do one time activity using its compile() method of the custom directive then process the element using link() method of the custom directive based on the scope of the directive.
What is constant
constants are used to pass values at config phase considering the fact that value cannot be used to be passed during config phase. mainApp.constant("configParam", "constant value");
What is the difference between service and factory methods?
factory method is used to define a factory which can later be used to create services as and when required whereas service method is used to create a service whose purpose is to do some defined task.
Explain the filter filter
filter filter is used to filter the array to a subset of it based on provided criteria. In below example, to display only required subjects, we've used subjectName as filter. Enter subject: <input type = "text" ng-model = "subjectName"> Subject: <ul> <li ng-repeat = "subject in student.subjects | filter: subjectName"> {{ subject.name + ', marks:' + subject.marks }} </li> </ul>
What is the core module in angular?
ng is the core module
Explain the ng-app directive.
ng-app directive defines and links an AngularJS application to HTML. It also indicate the start of the application.
Explain the ng-bind directive.
ng-bind directive binds the AngularJS Application data to HTML tags. ng-bind updates the model created by ng-model directive to be displayed in the html tag whenever user input something in the control or updates the html control's data when model data is updated by controller.
Explain the ng-click directive
ng-click directive represents a AngularJS click event. In below example, we've added ng-click attribute to a HTML button and added an expression to updated a model. Then we can see the variation. <p>Total click: {{ clickCounter }}</p></td> <button ng-click = "clickCounter = clickCounter + 1">Click Me!</button>
Explain the ng-controller directive.
ng-controller directive tells AngularJS what controller to use with this view. AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter which refers to the application/module that controller is to control.
Explain the ng-disabled directive
ng-disabled directive disables a given control. In below example, we've added ng-disabled attribute to a HTML button and pass it a model. Then we've attached the model to an checkbox and can see the variation. <input type = "checkbox" ng-model = "enableDisableButton">Disable Button <button ng-disabled = "enableDisableButton">Click Me!</button>
Explain the ng-hide directive
ng-hide directive hides a given control. In below example, we've added ng-hide attribute to a HTML button and pass it a model. Then we've attached the model to a checkbox and can see the variation. <input type = "checkbox" ng-model = "showHide2">Hide Button <button ng-hide = "showHide2">Click Me!</button>
Explain the ng-init directive.
ng-init directive initializes an AngularJS Application data. It is used to put values to the variables to be used in the application.
Explain the ng-model directive.
ng-model directive binds the values of AngularJS application data to HTML input controls. It creates a model variable which can be used with the html page and within the container control( for example, div) having ng-app directive.
Explain the ng-repeat directive.
ng-repeat directive repeats html elements for each item in a collection.
Explain the ng-show directive
ng-show directive shows a given control. In below example, we've added ng-show attribute to a HTML button and pass it a model. Then we've attached the model to a checkbox and can see the variation. <input type = "checkbox" ng-model = "showHide1">Show Button <button ng-show = "showHide1">Click Me!</button>
Explain the orderby filter
orderby filter orders the array based on provided criteria. In below example, to order subjects by marks, we've used orderBy marks. Subject: <ul> <li ng-repeat = "subject in student.subjects | orderBy:'marks'"> {{ subject.name + ', marks:' + subject.marks }} </li> </ul>
What is a provider?
provider is used by AngularJS internally to create services, factory etc. during config phase(phase during which AngularJS bootstraps itself). The below mention script can be used to create MathService that we've created earlier. Provider is a special factory method with a method get() which is used to return the value/service/factory. //define a module var mainApp = angular.module("mainApp", []); ... //create a service using provider which defines a method square to return square of a number. mainApp.config(function($provide) { $provide.provider('MathService', function() { this.$get = function() { var factory = {}; factory.multiply = function(a, b) { return a * b; } return factory; }; }); });