AngularJS interview questions

AngularJS quiz questions

  • 1.

    Explain what is Angular Expression? Explain what is key difference between angular expressions and JavaScript expressions?

    Answer:

    Like JavaScript,  Angular expressions are code snippets that are usually placed in binding such as {{ expression }}

    The key difference between the JavaScript expressions and Angular expressions

    • Context : In Angular, the expressions are evaluated against a scope object, while the Javascript expressions are evaluated against the global window
    • Forgiving: In Angular expression evaluation is forgiving to null and undefined, while in Javascript undefined properties generates TypeError or ReferenceError
    • No Control Flow Statements: Loops, conditionals or exceptions cannot be used in an angular expression
    • Filters: To format data before displaying it you can use filters
    View
  • 2.

    Explain what is services in AngularJS ?

    Answer:

    In AngularJS services are the singleton objects or functions that are used for carrying out specific tasks.  It holds some business logic and these function can be called as controllers, directive, filters and so on.

    View
  • 3.

    Explain what is scope in AngularJS ?

    Answer:

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

    View
  • 4.

    Explain what are the key features of AngularJS ?

    Answer:

    The key features of AngularJS are

    • Scope
    • Controller
    • Model
    • View
    • Services
    • Data Binding
    • Directives
    • Filters
    • Testable
    View
  • 5.

    What is AngularJS?

    Answer:

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

    View
  • 6.

    How do you disable a button depending on a checkbox’s state?

    Answer:

    We can use the ng-disabled directive and bind its condition to the checkbox’s state.

    <body ng-app>
    	<label><input type="checkbox" ng-model="checked"/>Disable Button</label>
    	<button ng-disabled="checked">Select me</button>
    </body>
    View
  • 7.

    How would you react on model changes to trigger some further action? For instance, say you have an input text field called email and you want to trigger or execute some code as soon as a user starts to type in their email.

    Answer:

    We can achieve this using $watch function in our controller.

    function MyCtrl($scope) {
    	$scope.email = "";
    
    	$scope.$watch("email", function(newValue, oldValue) {
    		if ($scope.email.length > 0) {
    			console.log("User has started writing into email");
    		}
    	});
    }
    View
  • 8.

    How do you hide an HTML element via a button click in AngularJS?

    Answer:

    You can do this by using the ng-hide directive in conjunction with a controller we can hide an HTML element on button click.

    <div ng-controller="MyCtrl">
    	<button ng-click="hide()">Hide element</button>
    	<p ng-hide="isHide">Hello World!</p>
    </div>
    function MyCtrl($scope){
    	$scope.isHide = false;
    	$scope.hide = function(){
    		$scope.isHide = true;
    	}
    }
    View
  • 9.

    How would you implement application-wide exception handling in your Angular app?

    Answer:

    Angular has a built-in error handler service called $exceptionHandler which can easily be overriden as seen below:

    myApp.factory('$exceptionHandler', function($log, ErrorService) {
        return function(exception, cause) {
            
            if (console) {
                $log.error(exception);
                $log.error(cause);
            }
    
            ErrorService.send(exception, cause);
        };
    });

    This is very useful for sending errors to third party error logging services or helpdesk applications. Errors trapped inside of event callbacks are not propagated to this handler, but can manually be relayed to this handler by calling $exceptionHandler(e) from within a try catch block.

    View
  • 10.

    How would you validate a text input field for a twitter username, including the @ symbol?

    Answer:

    You would use the ngPattern directive to perform a regex match that matches Twitter usernames. The same principal can be applied to validating phone numbers, serial numbers, barcodes, zip codes and any other text input.

    The official documentation can be found here.

    View
  • 11.

    How would you programatically change or adapt the template of a directive before it is executed and transformed?

    Answer:

    You would use the compile function. The compile function gives you access to the directive’s template before transclusion occurs and templates are transformed, so changes can safely be made to DOM elements. This is very useful for cases where the DOM needs to be constructed based on runtime directive parameters.

    Read more about it here.

    View
  • 12.

    What is an interceptor? What are common uses of it?

    Answer:

    An interceptor is a middleware code where all the $http requests go through.

    The interceptor is a factory that are registered in $httpProvider. You have 2 types of requests that go through the interceptor, request and response (with requestError and responseErrorrespectively). This piece of code is very useful for error handling, authentication or middleware in all the requests/responses.

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

    View
  • 13.

    What is a singleton pattern and where we can find it in Angularjs?

    Answer:

    Is a great pattern that restricts the use of a class more than once. We can find singleton pattern in angular in dependency injection and in the services.

    In a sense, if you do 2 times ‘new Object()‘ without this pattern, you will be alocating 2 pieces of memory for the same object. With singleton pattern, if the object exists, you reuse it.

    Source: http://joelhooks.com/blog/2013/05/01/when-is-a-singleton-not-a-singleton/

    View
  • 14.

    What is DDO Directive Definition Object?

    Answer:

    “DDO is an object used while creating a custome directive. A standard DDO object has following parameters.

    var directiveDefinitionObject = {
        priority: 0,
        template: '

    ', // or // function(tElement, tAttrs) { ... }, // or // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... }, transclude: false, restrict: 'A', templateNamespace: 'html', scope: false, controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, controllerAs: 'stringIdentifier', bindToController: false, require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'], compile: function compile(tElement, tAttrs, transclude) { return { pre: function preLink(scope, iElement, iAttrs, controller) { ... }, post: function postLink(scope, iElement, iAttrs, controller) { ... } } // or // return function postLink( ... ) { ... } }, // or // link: { // pre: function preLink(scope, iElement, iAttrs, controller) { ... }, // post: function postLink(scope, iElement, iAttrs, controller) { ... } // } // or // link: function postLink( ... ) { ... } };"

    This question mainly judges whether candidate knows about creating custom directives.

    Read more at https://docs.angularjs.org/guide/directive

    View
  • 15.

    What are Directives?

    Answer:

    Directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children. Angular comes with a set of these directives built-in, like ngBind, ngModel, and ngClass. Much like you create controllers and services, you can create your own directives for Angular to use. When Angular bootstraps your application, the HTML compiler traverses the DOM matching directives against the DOM elements.

    This question is important because directives define the UI while defining a single page app. You need to be very clear about how to create a new custom directive or use the existing ones already pre-build in AngularJS.

    Source: https://docs.angularjs.org/guide/directive

    View
  • 16.

    Explain what is a $scope in AngularJS

    Answer:

    Scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events. Scopes are objects that refer to the model. They act as glue between controller and view.

    This question is important as it will judge a persons knowledge about a $scope object, and it is one of the most important concepts in AngularJS. Scope acts like a bridge between view and model.

    Source: https://docs.angularjs.org/guide/scope

    View
  • 17.

    How do you reset a $timeout, $interval(), and disable a $watch()?

    Answer:

    To reset a timeout and/or $interval, assign the result of the function to a variable and then call the .cancel() function.

    var customTimeout = $timeout(function () {
      // arbitrary code
    }, 55);
    
    $timeout.cancel(customTimeout);
    

    to disable $watch(), we call its deregistration function. $watch() then returns a deregistration function that we store to a variable and that will be called for cleanup

    var deregisterWatchFn = $scope.$on(‘$destroy’, function () {
        // we invoke that deregistration function, to disable the watch
        deregisterWatchFn();
    });
    View
  • 18.

    When should you use an attribute versus an element?

    Answer:

    Use an element when you are creating a component that is in control of the template. Use an attribute when you are decorating an existing element with new functionality.

    This topic is important so developers can understand the several ways a directive can be used inside a view and when to use each way.

    Sources: https://docs.angularjs.org/api/ng/service/$compile#directive-definition-object

    View
  • 19.

    When creating a directive, it can be used in several different ways in the view. Which ways for using a directive do you know? How do you define the way your directive will be used?

    Answer:

    When you create a directive, it can be used as an attribute, element or class name. To define which way to use, you need to set the restrict option in your directive declaration.

    The restrict option is typically set to:

    ‘A’ – only matches attribute name
    ‘E’ – only matches element name
    ‘C’ – only matches class name

    These restrictions can all be combined as needed:

    ‘AEC’ – matches either attribute or element or class name

    For more information, feel free to check out the AngularJS documentation.

    View
  • 20.

    What is the role of services in AngularJS and name any services made available by default?

    Answer:

    – AngularJS Services are objects that provide separation of concerns to an AngularJS app.
    – AngularJS Services can be created using a factory method or a service method.
    – Services are singleton components. All components of the application (into which the service is injected) will work with single instance of the service.
    – An AngularJS service allows developing of business logic without depending on the View logic which will work with it.

    Few of the inbuilt services in AngularJS are:
    – the $http service: The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser’s XMLHttpRequest object or via JSONP
    – the $log service: Simple service for logging. Default implementation safely writes the message into the browser’s console
    – the $anchorScroll: it scrolls to the element related to the specified hash or (if omitted) to the current value of $location.hash()
    Why should one know about AngularJS Services, you may ask. Well, understanding the purpose of AngularJS Services helps bring modularity to AngularJS code.
    Services are the best may to evolve reusable API within and AngularJS app

    Overview:

    • AngularJS Services help create reusable components.
    • A Service can be created either using the service() method or the factory() method.
    • A typical service can be injected into another service or into an AngularJS Controller.

    Source:
    – https://docs.angularjs.org/guide/services
    – http://www.tutorialspoint.com/angularjs/angularjs_services.htm

    View

© 2017 QuizBucket.org