Skip to content

Latest commit

 

History

History
1243 lines (833 loc) · 50.9 KB

angularjs.md

File metadata and controls

1243 lines (833 loc) · 50.9 KB

AngularJS

Why to use AngularJS?

What is the difference between "ng-show"/"ng-hide" and "ng-if" directives?

Does AngularJS has dependency on jQuery?

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

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

What are the AngularJS features?

When dependent modules of a module are loaded?

What is Angular’s prefixes $ and $$?

What are Filters in AngularJS?

What are Directives in AngularJS?

What are Directives?

Explain what is a "$scope" in AngularJS

What directive would you use to hide elements from the HTML DOM by removing them from that DOM not changing their styling?

What is the difference between one-way binding and two-way binding?

What is auto bootstrap process in AngularJS?

How would you specify that a scope variable should have one-time binding only?

What is scope in AngularJS?

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

What is scope hierarchy?

How do you share data between controllers?

What are the basic steps to unit test an AngularJS filter?

What are the basic steps to unit test an AngularJS filter?

What are the advantage of AngularJS?

Explain what is services in AngularJS

Explain what is directive and mention what are the different types of Directive?

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

Explain what is the difference between link and compile in AngularJS?

How would you react on model changes to trigger some further action?

What is jQLite/jQuery Lite?

What should be the maximum number of concurrent “watches”?

What is a digest cycle in AngularJS?

Where should we implement the DOM manipulation in AngularJS?

Is it a good or bad practice to use AngularJS together with jQuery?

If you were to migrate from Angular 1.4 to Angular 1.5, what is the main thing that would need refactoring?

Explain what Angular JS routes does?

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

What is restrict option in directive?

How would you make an Angular service return a promise?

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

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

What are different ways to invoke a directive?

What is the role of ng-app, ng-init and ng-model directives?

How to access jQLite?

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

What is manual bootstrap process in AngularJS?

What makes the angular.copy() method so powerful?

Explain what is linking function and type of linking function?

Explain what is injector?

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?

When should you use an attribute versus an element?

Explain what is DI (Dependency Injection ) and how an object or function can get a hold of its dependencies?

Explain how $scope.$apply() works?

How AngularJS is compiled?

What is DDO (Directive Definition Object)?

Can you define multiple restrict options on a directive?

What is the difference between $scope and scope?

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

What is $scope and $rootScope?

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

How AngularJS compilation is different from other JavaScript frameworks?

How Directives are compiled?

What are Compile, Pre and Post linking in AngularJS?

Why to use AngularJS?

There are following reasons to choose AngularJS as a web development framework:

  1. It is based on MVC pattern which helps you to organize your web apps or web application properly.
  2. It extends HTML by attaching directives to your HTML markup with new attributes or tags and expressions in order to define very powerful templates.
  3. It also allows you to create your own directives, making reusable components that fill your needs and abstract your DOM manipulation logic.
  4. It supports two-way data binding i.e. connects your HTML (views) to your JavaScript objects (models) seamlessly. In this way any change in model will update the view and vice versa without any DOM manipulation or event handling.
  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 to use some utility code to fullfil your need. For example, it provides $http service to communicate with REST service.
  7. It supports dependency injection which helps you to test your angular app code very easily.
  8. Also, AngularJS is mature community to help you. It has widely support over the internet.
Source

[↑] Back to top

What is the difference between "ng-show"/"ng-hide" and "ng-if" directives?

ng-show/ng-hide will always insert the DOM element, but will display/hide it based on the condition. ng-if will not insert the DOM element until the condition is not fulfilled.

ng-if is better when we needed the DOM to be loaded conditionally, as it will help load page bit faster compared to ng-show/ng-hide.

We only need to keep in mind what the difference between these directives is, so deciding which one to use totally depends on the task requirements.

Source

[↑] Back to top

Does AngularJS has dependency on jQuery?

AngularJS has no dependency on jQuery library. But it can be used with jQuery library.

Source

[↑] Back to top

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

This can be done by using the ng-hide directive in conjunction with a controller to 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;
	};
}
Source

[↑] Back to top

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

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 the you do 2 times new Object() without this pattern, the you will be alocating 2 pieces of memory for the same object. With singleton pattern, if the object exists, it'll be reused.

Source

[↑] Back to top

What are the AngularJS features?

The features of AngularJS are listed below:

  1. Modules
  2. Directives
  3. Templates
  4. Scope
  5. Expressions
  6. Data Binding
  7. MVC (Model, View & Controller)
  8. Validations
  9. Filters
  10. Services
  11. Routing
  12. Dependency Injection
  13. Testing
Source

[↑] Back to top

When dependent modules of a module are loaded?

A module might have dependencies on other modules. The dependent modules are loaded by angular before the requiring module is loaded.

In other words the configuration blocks of the dependent modules execute before the configuration blocks of the requiring module. The same is true for the run blocks. Each module can only be loaded once, even if multiple other modules require it.

Source

[↑] Back to top

What is Angular’s prefixes $ and $$?

To prevent accidental name collisions with your code, Angular prefixes names of public objects with $ and names of private objects with $$. So, do not use the $ or $$ prefix in your code.

Source

[↑] Back to top

What are Filters in AngularJS?

Filters are used to format data before displaying it to the user. They can be used in view templates, controllers, services and directives. There are some built-in filters provided by AngularJS like as Currency, Date, Number, OrderBy, Lowercase, Uppercase etc. You can also create your own filters.

Filter Syntax:

{{ expression | filter}}

Source

[↑] Back to top

What are Directives in AngularJS?

AngularJS directives are a combination of AngularJS template markups (HTML attributes or elements, or CSS classes) and supporting JavaScript code. The JavaScript directive code defines the template data and behaviors of the HTML elements.

AngularJS directives are used to extend the HTML vocabulary i.e. they decorate html elements with new behaviors and help to manipulate html elements attributes in interesting way.

There are some built-in directives provided by AngularJS like as ng-app, ng-controller, ng-repeat, ng-model etc.

Source

[↑] Back to top

What are Directives?

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.

Source

[↑] Back to top

Explain what is a "$scope" in AngularJS

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.

Source

[↑] Back to top

What directive would you use to hide elements from the HTML DOM by removing them from that DOM not changing their styling?

The ngIf Directive, when applied to an element, will remove that element from the DOM if it’s condition is false.

Source

[↑] Back to top

What is the difference between one-way binding and two-way binding?

  • One way binding implies that the scope variable in the html will be set to the first value its model is bound to (i.e. assigned to)
  • Two way binding implies that the scope variable will change it’s value everytime its model is assigned to a different value
Source

[↑] Back to top

What is auto bootstrap process in AngularJS?

Angular initializes automatically upon DOMContentLoaded event or when the angular.js script is downloaded to the browser and the document.readyState is set to complete. At this point AngularJS looks for the ng-app directive which is the root of angular app compilation and tells about AngularJS part within DOM. When the ng-app directive is found then Angular will:

  1. Load the module associated with the directive.
  2. Create the application injector.
  3. Compile the DOM starting from the ng-app root element. This process is called auto-bootstrapping.
<html>
<body ng-app="myApp">
<div ng-controller="Ctrl"> Hello {{msg}}!
</div>
    <script src="lib/angular.js"></script>
    <script>
var app = angular.module('myApp', []); app.controller('Ctrl', function ($scope) {
              $scope.msg = 'World';
          });
    </script>
</body>
</html>
Source

[↑] Back to top

How would you specify that a scope variable should have one-time binding only?

By using “::” in front of it.

Source

[↑] Back to top

What is scope in AngularJS?

Scope is a JavaScript object that refers to the application model. It acts as a context for evaluating angular expressions. Basically, it acts as glue between controller and view.

Scopes are hierarchical in nature and follow the DOM structure of your AngularJS app. AngularJS has two scope objects: $rootScope and $scope.

Source

[↑] Back to top

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

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>
Source

[↑] Back to top

What is scope hierarchy?

The $scope object used by views in AngularJS are organized into a hierarchy. There is a root scope, and the $rootScope can has one or more child scopes. Each controller has its own $scope (which is a child of the $rootScope), so whatever variables you create on $scope within controller, these variables are accessible by the view based on this controller.

For example, suppose you have two controllers: ParentController and ChildController as given below:

<html>
  <head>
    <script src="lib/angular.js"></script>
    <script>
      var app = angular.module('ScopeChain', []); app.controller("parentController", function ($scope) {
      	$scope.managerName = 'Shailendra Chauhan';
      	$scope.$parent.companyName = 'Dot Net Tricks'; //attached to $rootScope
      });
      app.controller("childController", function ($scope, $controller) {
                 $scope.teamLeadName = 'Deepak Chauhan';
             });
         
    </script>
  </head>
  <body ng-app="ScopeChain">
    <div ng-controller="parentController ">
      <table style="border:2px solid #e37112">
        <caption>Parent Controller</caption>
        <tr>
          <td>Manager Name</td>
          <td>{{managerName}}</td>
        </tr>
        <tr>
          <td>Company Name</td>
          <td>{{companyName}}</td>
        </tr>
        <tr>
          <td>
            <table ng-controller="childController" style="border:2px solid #428bca">
              <caption>Child Controller</caption>
              <tr>
                <td>Team Lead Name</td>
                <td>{{ teamLeadName }}</td>
              </tr>
              <tr>
                <td>Reporting To</td>
                <td>{{managerName}}</td>
              </tr>
              <tr>
                <td>Company Name</td>
                <td>{{companyName}}</td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </div>
  </body>
</html>
Source

[↑] Back to top

How do you share data between controllers?

Create an AngularJS service that will hold the data and inject it inside of the controllers.

Using a service is the cleanest, fastest and easiest way to test. However, there are couple of other ways to implement data sharing between controllers, like:

– Using events
– Using $parent, nextSibling, controllerAs, etc. to directly access the controllers
– Using the $rootScope to add the data on (not a good practice)

The methods above are all correct, but are not the most efficient and easy to test.

Source

[↑] Back to top

What are the basic steps to unit test an AngularJS filter?

  • Inject the module that contains the filter.
  • Provide any mocks that the filter relies on.
  • Get an instance of the filter using $filter('yourFilterName').
  • Assert your expectations.
Source

[↑] Back to top

What are the basic steps to unit test an AngularJS filter?

  1. Inject the module that contains the filter.
  2. Provide any mocks that the filter relies on.
  3. Get an instance of the filter using $filter('yourFilterName').
  4. Assert your expectations.
Source

[↑] Back to top

What are the advantage of AngularJS?

There are following advantages of AngularJS:

  1. Data Binding - AngularJS provides a powerful data binding mechanism to bind data to HTML elements by using scope.
  2. Customize & Extensible - AngularJS is customized and extensible as per you requirement. You can create your own custom components like directives, services etc.
  3. Code Reusability - AngularJS allows you to write code which can be reused. For example custom directive which you can reuse.
  4. Support – AngularJS is mature community to help you. It has widely support over the internet. Also, AngularJS is supported by Google which gives it an advantage.
  5. Compatibility - AngularJS is based on JavaScript which makes it easier to integrate with any other JavaScript library and runnable on browsers like IE, Opera, FF, Safari, Chrome etc.
  6. Testing - AngularJS is designed to be testable so that you can test your AngularJS app components as easy as possible. It has dependency injection at its core, which makes it easy to test.
Source

[↑] Back to top

Explain what is services in AngularJS

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.

Source

[↑] Back to top

Explain what is directive and mention what are the different types of Directive?

During compilation process when specific HTML constructs are encountered a behaviour or function is triggered, this function is referred as directive. It is executed when the compiler encounters it in the DOM.

Different types of directives are:

  • Element directives
  • Attribute directives
  • CSS class directives
  • Comment directives
Source

[↑] Back to top

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

We should 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.

Source

[↑] Back to top

Explain what is the difference between link and compile in AngularJS?

  • Compile function: It is used for template DOM Manipulation and collect all of the directives.
  • Link function: It is used for registering DOM listeners as well as instance DOM manipulation. It is executed once the template has been cloned.
Source

[↑] Back to top

How would you react on model changes to trigger some further action?

This can be achieved by using $watch function in the 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');
		}
	});
}
Source

[↑] Back to top

What is jQLite/jQuery Lite?

jQLite is a subset of jQuery that is built directly into AngularJS. jQLite provides you all the useful features of jQuery. In fact it provides you limited features or functions of jQuery.

Source

[↑] Back to top

What should be the maximum number of concurrent “watches”?

To reduce memory consumption and improve performance it is a good idea to limit the number of watches on a page to 2,000. A utility called ng-stats can help track your watch count and digest cycles.

Source

[↑] Back to top

What is a digest cycle in AngularJS?

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.

Source

[↑] Back to top

Where should we implement the DOM manipulation in AngularJS?

In the directives. DOM Manipulations should not exist in controllers, services or anywhere else but in directives.

Source

[↑] Back to top

Is it a good or bad practice to use AngularJS together with jQuery?

It is definitely a bad practice. We need to stay away from jQuery and try to realize the solution with an AngularJS approach. jQuery takes a traditional imperative approach to manipulating the DOM, and in an imperative approach, it is up to the programmer to express the individual steps leading up to the desired outcome.

AngularJS, however, takes a declarative approach to DOM manipulation. Here, instead of worrying about all of the step by step details regarding how to do the desired outcome, we are just declaring what we want and AngularJS worries about the rest, taking care of everything for us.

Source

[↑] Back to top

If you were to migrate from Angular 1.4 to Angular 1.5, what is the main thing that would need refactoring?

Changing .directive to .component to adapt to the new Angular 1.5 components.

Source

[↑] Back to top

Explain what Angular JS routes does?

Routes enable you to create different URLs for different content in your application. Different URLs for different content enables user to bookmark URLs to specific content. Each such bookmarkable URL in AngularJS is called a route.

Source

[↑] Back to top

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

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
Source

[↑] Back to top

What is restrict option in directive?

The restrict option in angular directive, is used to specify how a directive will be invoked in your angular app i.e. as an attribute, class, element or comment.

There are four valid options for restrict:

'A' (Attribute)- <span my-directive></span>
'C' (Class)- <span class="my-directive:expression;"></span>
'E' (Element)- <my-directive></my-directive>
'M' (Comment)- <!-- directive: my-directive expression -->
Source

[↑] Back to top

How would you make an Angular service return a promise?

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

[↑] Back to top

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

AngularJS Services are objects that provide separation of concerns to an AngularJS app. These can be created using a factory method or a service method. Services are singleton components and 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

[↑] Back to top

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

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();
});
Source

[↑] Back to top

What are different ways to invoke a directive?

There are four methods to invoke a directive in your angular app which are equivalent.

  • As an attribute
<span my-directive></span
  • As a class
<span class="my-directive: expression;"></span>
  • As an element
<my-directive></my-directive>
  • As a comment
<!-- directive: my-directive expression -->
Source

[↑] Back to top

What is the role of ng-app, ng-init and ng-model directives?

The main role of these directives is explained as:

  • ng-app - Initialize the angular app.
  • ng-init - Initialize the angular app data.
  • ng-model - Bind the html elem
Source

[↑] Back to top

How to access jQLite?

jQuery lite or the full jQuery library if available, can be accessed via the AngularJS code by using the element() function in AngularJS. Basically, angular.element() is an alias for the jQuery function.

Source

[↑] Back to top

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

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

The interceptor is a factory that are registered in $httpProvider. There are two types of requests that go through the interceptor, request and response (with requestError and responseError respectively).

This piece of code is very useful for error handling, authentication or middleware in all the requests/responses.

Source

[↑] Back to top

What is manual bootstrap process in AngularJS?

You can manually initialized your angular app by using angular.bootstrap() function. This function takes the modules as parameters and should be called within angular.element(document).ready() function. The angular.element(document).ready() function is fired when the DOM is ready for manipulation.

<html>
<body>
    <div ng-controller="Ctrl">
Hello {{msg}}! </div>
    <script src="lib/angular.js"></script>
    <script>
        var app = angular.module('myApp', []);
        app.controller('Ctrl', function ($scope) {
              $scope.msg = 'World';
          });
        //manual bootstrap process
angular.element(document).ready(function () { angular.bootstrap(document, ['myApp']);
});
    </script>
</body>
</html>

Note:

  • You should not use the ng-app directive when manually bootstrapping your app.
  • You should not mix up the automatic and manual way of bootstrapping your app.
  • Define modules, controller, services etc. before manually bootstrapping your app as defined in above example.
Source

[↑] Back to top

What makes the angular.copy() method so powerful?

It creates a deep copy of the variable.

A deep copy of a variable means it doesn’t point to the same memory reference as that variable. Usually assigning one variable to another creates a “shallow copy”, which makes the two variables point to the same memory reference. Therefore if one is changed, the other changes as well.

Source

[↑] Back to top

Explain what is linking function and type of linking function?

Link combines the directives with a scope and produce a live view. For registering DOM listeners as well as updating the DOM, link function is responsible. After the template is cloned it is executed.

  • Pre-linking function: Pre-linking function is executed before the child elements are linked. It is not considered as the safe way for DOM transformation.
  • Post linking function: Post linking function is executed after the child elements are linked. It is safe to do DOM transformation by post-linking function
Source

[↑] Back to top

Explain what is injector?

An injector is a service locator. It is used to retrieve object instances as defined by provider, instantiate types, invoke methods and load modules. There is a single injector per Angular application, it helps to look up an object instance by its name.

Source

[↑] Back to top

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?

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
Source

[↑] Back to top

When should you use an attribute versus an element?

  • 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.
Source

[↑] Back to top

Explain what is DI (Dependency Injection ) and how an object or function can get a hold of its dependencies?

DI or Dependency Injection is a software design pattern that deals with how code gets hold of its dependencies. In order to retrieve elements of the application which is required to be configured when module gets loaded , the operation “config” uses dependency injection.

These are the ways that object uses to hold of its dependencies:

  • Typically using the new operator, dependency can be created
  • By referring to a global variable, dependency can be looked up
  • Dependency can be passed into where it is required
Source

[↑] Back to top

Explain how $scope.$apply() works?

$scope.$apply re-evaluates all the declared ng-models and applies the change to any that have been altered (i.e. assigned to a new value) Explanation: scope.scope.scope.apply() is one of the core angular functions that should never be used explicitly, it forces the angular engine to run on all the watched variables and all external variables and apply the changes on their values

Source

[↑] Back to top

How AngularJS is compiled?

Angular's HTML compiler allows you to teach the browser new HTML syntax. The compiler allows you to attach new behaviors or attributes to any HTML element. Angular calls these behaviors as directives. AngularJS compilation process takes place in the web browser; no server side or pre-compilation step is involved. Angular uses $compiler service to compile your angular HTML page. The angular' compilation process begins after your HTML page (static DOM) is fully loaded. It happens in two phases:

  1. Compile - It traverse the DOM and collect all of the directives. The result is a linking function.
  2. Link - It combines the directives with a scope and produces a live view. Any changes in the scope model are reflected in the view, and any user interactions with the view are reflected in the scope model.

The concept of compile and link comes from C language, where you first compile the code and then link it to actually execute it. The process is very much similar in AngularJS as well.

Source

[↑] Back to top

What is DDO (Directive Definition Object)?

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

var directiveDefinitionObject = {
	priority: 0,
	template: '<div></div>', // 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( ... ) { ... }
};
Source

[↑] Back to top

Can you define multiple restrict options on a directive?

You can also specify multiple restrict options to support more than one methods of directive invocation as an element or an attribute. Make sure all are specified in the restrict keyword as: restrict: 'EA' .

Source

[↑] Back to top

What is the difference between $scope and scope?

The module factory methods like controller, directive, factory, filter, service, animation, config and run receive arguments through dependency injection (DI). In case of DI, you inject the scope object with the dollar prefix i.e. $scope. The reason is the injected arguments must match to the names of injectable objects followed by dollar ($) prefix. For example, you can inject the scope and element objects into a controller as given below:

module.controller('MyController', function ($scope, $element) { // injected arguments });

When the methods like directive linker function don’t receive arguments through dependency injection, you just pass the scope object without using dollar prefix i.e. scope. The reason is the passing arguments are received by its caller.

module.directive('myDirective', function () // injected arguments here {
    return {
        // linker function does not use dependency injection
        link: function (scope, el, attrs) {
	// the calling function will passes the three arguments to the linker: scope, element and attributes, in the same order
	} };
});

In the case of non-dependency injected arguments, you can give the name of injected objects as you wish. The above code can be re-written as:

module.directive("myDirective", function () {
	return {
        link: function (s, e, a) {
            // s == scope
	} };
});
// e == element

In short, in case of DI the scope object is received as $scope while in case of non-DI scope object is received as scope or with any name.

Source

[↑] Back to top

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

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.

Source

[↑] Back to top

What is $scope and $rootScope?

$scope - A $scope is a JavaScript object which is used for communication between controller and view. Basically, $scope binds a view (DOM element) to the model and functions defined in a controller.

$rootScope - The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope. For example, suppose you have two controllers: Ctrl1 and Ctrl2 as given below:

<!doctype html>
<html>
  <body ng-app="myApp">
    <div ng-controller="Ctrl1" style="border:2px solid blue; padding:5px"> Hello {{msg}}!
      <br />
      Hello {{name}}! (rootScope) 
    </div>
    <br />
    <div ng-controller="Ctrl2" style="border:2px solid green; padding:5px">
      Hello {{msg}}! <br />
      Hey {{myName}}! <br />
      Hi {{name}}! (rootScope) 
    </div>
    <script src="lib/angular.js"></script>
    <script>
      var app = angular.module('myApp', []); app.controller('Ctrl1', function ($scope, $rootScope) {
                  $scope.msg = 'World';
                  $rootScope.name = 'AngularJS';
              });
      app.controller('Ctrl2', function ($scope, $rootScope) { $scope.msg = 'Dot Net Tricks';
      $scope.myName = $rootScope.name;
      });
          
    </script>
  </body>
</html>
Source

[↑] Back to top

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

We should use the compile function. The compile function gives 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.

Source

[↑] Back to top

How AngularJS compilation is different from other JavaScript frameworks?

If you have worked on templates in other java script framework/library like backbone and jQuery, they process the template as a string and result as a string. You have to dumped this result string into the DOM where you wanted it with innerHTML().

AngularJS process the template in another way. It directly works on HTML DOM rather than strings and manipulates it as required. It uses two way data-binding between model and view to sync your data.

Source

[↑] Back to top

How Directives are compiled?

It is important to note that Angular operates on DOM nodes rather than strings. Usually, you don't notice this because when an html page loads, the web browser parses HTML into the DOM automatically. HTML compilation happens in three phases:

  1. The $compile traverses the DOM and looks for directives. For each directive it finds, it adds it to a list of directives.
  2. Once the entire DOM has been traversed, it will sort that list of directives by their priority. Then, each directive’s own compile function is executed, giving each directive the chance to modify the DOM itself. Each compile function returns a linking function, which is then composed into a combined linking function and returned.
  3. $compile links the template with the scope by calling the combined linking function from the previous step. This in turn will call the linking function of the individual directives, registering listeners on the elements and setting up $watch with the scope as each directive is configured to do.

The pseudo code for the above process is given below:

var $compile = ...; // injected into your code
var scope = ...;
var parent = ...; // DOM element where the compiled template can be appended
var html = '<div ng-bind="exp"></div>';
// Step 1: parse HTML into DOM element
var template = angular.element(html);
// Step 2: compile the template
var linkFn = $compile(template);
// Step 3: link the compiled template with the scope.
var element = linkFn(scope);
// Step 4: Append to DOM (optional)
parent.appendChild(element);
Source

[↑] Back to top

What are Compile, Pre and Post linking in AngularJS?

  • Compile – This compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. Use the compile function to change the original DOM (template element) before AngularJS creates an instance of it and before a scope is created.

  • Post-Link – This is executed after the child elements are linked. It is safe to do DOM transformation in the post- linking function. Use the post-link function to execute logic, knowing that all child elements have been compiled and all pre-link and post-link functions of child elements have been executed.

  • Pre-Link – This is executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking. Use the pre-link function to implement logic that runs when AngularJS has already compiled the child elements, but before any of the child element's post-link functions have been called.

<html>
  <head>
  <title>Compile vs Link</title>
  <script src="lib/angular.js"></script>
  <script type="text/javascript">
    var app = angular.module('app', []);

    function createDirective(name) {
      return function () {
        return {
          restrict: 'E',
          compile: function (tElem, tAttrs) {
            console.log(name + ': compile');

            return {
              pre: function (scope, iElem, attrs) {
                console.log(name + ': pre link');
              },
              post: function (scope, iElem, attrs) {
                console.log(name + ': post link');
              }
            }

          }
        }
      }
    };
    app.directive('levelOne', createDirective('level-One'));
    app.directive('levelTwo', createDirective('level-Two'));
    app.directive('levelThree', createDirective('level-Three'));
  </script>
  </head>
  <body ng-app="app">
    <level-one>
      <level-two>
        <level-three>
          Hello {{name}}
        </level-three>
      </level-two>
    </level-one>
  </body>
</html>

Output:

level-One: compile
level-Two: compile
level-Three: compile
level-One: pre link
level-Two: pre link
level-Three: pre link
level-Three: post link
level-Two: post link
level-One: post link
Source

[↑] Back to top