The largest Interview Solution Library on the web


Interview Questions
« Previous | 0 | 1 | 2 | 3 | 4 | Next »

41.How AngularJS is compiled?

Angular's HTML compiler allows you to teach the browser new HTML syntax. The compiler allows you to attach new behaviours or attributes to any HTML element. Angular calls these behaviours 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.

42.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.

43.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);

44.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>

45.What directives are used to show and hide HTML elements in AngularJS?

ng-show and ng-hide directives are used to show and hide HTML elements in the AngularJS based on an expression. When the expression is true for ng-show or ng-hide, HTML element(s) are shown or hidden from the page. When the expression is false for ng-show or ng-hide, HTML element(s) are hidden or shown on the page.

<div ng-controller="MyCtrl">
<div ng-show="data.isShow">ng-show Visible</div>
<div ng-hide="data.isHide">ng-hide Invisible</div>
</div>
<script>
var app = angular.module("app", []);
app.controller("MyCtrl", function ($scope) {
$scope.data = {}; $scope.data.isShow = true;
$scope.data.isHide = true;
});
</script>

46.Explain directives ng-if, ng-switch and ng-repeat?

ng-if – This directive can add / remove HTML elements from the DOM based on an expression. If the expression is true, it add HTML elements to DOM, otherwise HTML elements are removed from the DOM.

<div ng-controller="MyCtrl">
<div ng-if="data.isVisible">ng-if Visible</div>
</div>
<script>
var app = angular.module("app", []);
app.controller("MyCtrl", function ($scope) {
$scope.data = {};
$scope.data.isVisible = true;
});
</script>

ng-switch – This directive can add / remove HTML elements from the DOM conditionally based on scope expression.

<div ng-controller="MyCtrl">
<div ng-switch on="data.case">
<div ng-switch-when="1">Shown when case is 1</div>
<div ng-switch-when="2">Shown when case is 2</div>
<div ng-switch-default>Shown when case is anything else than 1 and 2</div>
</div>
</div>
<script>
var app = angular.module("app", []);
app.controller("MyCtrl", function ($scope) {
$scope.data = {};
$scope.data.case = true; });
</script>

ng-repeat - This directive is used to iterate over a collection of items and generate HTML from it.

<div ng-controller="MyCtrl">
<ul>
<li ng-repeat="name in names">
{{ name }}
</li>
</ul>
</div>
<script>
var app = angular.module("app", []);
app.controller("MyCtrl", function ($scope) {
$scope.names = ['Aarif', 'Naushad', 'Naushaad'];
});
</script>

47.What are ng-repeat special variables?

The ng-repeat directive has a set of special variables which you are useful while iterating the collection. These variables are as follows:

  • $index
  • $first
  • $middle
  • $last

<html>
<head>
<script src="lib/angular.js"></script>
<script>
var app = angular.module("app", []);
app.controller("ctrl", function ($scope) {
$scope.friends = [{ name: 'Aarif', gender: 'boy' },
{ name: 'zene', gender: 'girl' },
{ name: 'farrru', gender: 'boy' },
{ name: 'sofi', gender: 'girl' }
];
});
</script>
</head>
<body ng-app="app">
<div ng-controller="ctrl">
<ul class="example-animate-container">
<li ng-repeat="friend in friends">
<div>
[{{$index + 1}}] {{friend.name}} is a {{friend.gender}}.
<span ng-if="$first">
<strong>(first element found)</strong>
</span>
<span ng-if="$middle">
<strong>(middle element found)</strong>
</span> <span ng-if="$last">
<strong>(last element found)</strong>
</span>
</div>
</li>
</ul>
</div>
</body>
</html>

Output

  • [1]Aarif is a boy.(first element found)
  • [2]zene is a girl.(middle element found)
  • [3]farrru is aboy.(middle element found)
  • [4]sofi is a girl.(last element found)

The $index contains the index of the element being iterated. The $first, $middle and $last returns a boolean value depending on whether the current item is the first, middle or last element in the collection being iterated.

48.What are Templates in AngularJS?

AngularJS templates are just plain old HTML that contains Angular-specific elements and attributes. AngularJS used these templates to show information from the model and controller.

Creating an AngularJS template

<html ng-app>
<!-- body tag with ngController directive -->
<body ng-controller="MyController">
<input ng-model="txtName" value="Aarif"/>
<!-- button tag with ng-click directive & string expression 'btnText' wrapped in "{{ }}"
markup -->
<button ng-click="changeName()">{{btnText}}</button>
<script src="angular.js">
</body>
</html>

49.What is ng-include and when to use it?

ng-include is a directive which is used to include external HTML fragments from other files into the view's HTML template.

For example, index.html file can be added inside the div element by using ng-include directive as an attribute.

<div ng-controller="MyCtrl">
<div ng-include="'index.html'"></div>
</div>

ng-include directive is limited to load HTML fragments file from same domain but it doesn’t work for cross-domain i.e. it can’t load the HTML fragments file from different domains.

50.What angular components can be defined within AngularJS templates?

AngularJS templates can have following angular elements and attributes:

1. Directive
2. Angular Markup ('{{}}')
3. Filters
4. Form Controls

51.What is data binding in AngularJS?

AngularJS data-binding is the most useful feature which saves you from writing boilerplate code (i.e. the sections of code which is included in many places with little or no alteration). Now, developers are not responsible for manually manipulating the DOM elements and attributes to reflect model changes. AngularJS provides two-way data-binding to handle the synchronization of data between model and view.

52.Explain Two-way and One-way data binding in AngularJS?

Two-way data binding - It is used to synchronize the data between model and view. It means, any change in model will update the view and vice versa. ng-model directive is used for two-way data binding.

One-way data binding - This binding is introduced in Angular 1.3. An expression that starts with double colon (::), is considered a one-time expression i.e. one-way binding.

Two-Way and One-Way data binding Example

<div ng-controller="MyCtrl">
<label>Name (two-way binding): <input type="text" ng-model="name" /></label>
<strong>Your name (one-way binding):</strong> {{::name}}<br />
<strong>Your name (normal binding):</strong> {{name}}
</div>
<script>
var app = angular.module('app', []);
app.controller("MyCtrl", function ($scope) {
$scope.name = "aarif mohammad" })
</script>

53.What is issue with two-way data binding? OR Why one-way data binding is introduced?

In order to make data-binding possible, Angular uses $watch APIs to observe model changes on the scope. Angular registered watchers for each variable on scope to observe the change in its value. If the value, of variable on scope is changed then the view gets updated automatically.

This automatic change happens because of $digest cycle is triggered. Hence, Angular processes all registered watchers on the current scope and its children and checks for model changes and calls dedicated watch listeners until the model is stabilized and no more listeners are fired. Once the $digest loop finishes the execution, the browser re-renders the DOM and reflects the changes.

By default, every variable on a scope is observed by the angular. In this way, unnecessary variable are also observed by the angular that is time consuming and as a result page is becoming slow.

Hence to avoid unnecessary observing of variables on scope object, angular introduced one-way data binding.

54.How AngularJS handle data binding?

AngularJS handle data-binding mechanism with the help of three powerful functions: $watch(), $digest() and $apply(). Most of the time AngularJS will call the $scope.$watch() and $scope.$digest() functions for you, but in some cases you may have to call these functions yourself to update new values.

55.What is the difference between $watch, $digest and $apply?

$watch() - This function is used to observe changes in a variable on the $scope. It accepts three parameters: expression, listener and equality object, where listener and equality object are optional parameters.

$watch(watchExpression, listener, [objectEquality])

<html>
<head>
<title>AngularJS Watch</title>
<script src="lib/angular.js"></script>
<script>
var myapp = angular.module("myapp", []);
var myController = myapp.controller("myController", function ($scope) {
$scope.name = 'dotnet-tricks.com';
$scope.counter = 0;
//watching change in name value
$scope.$watch('name', function (newValue, oldValue) {
$scope.counter = $scope.counter + 1;
});
});
</script>
</head>
<body ng-app="myapp" ng-controller="myController">
<input type="text" ng-model="name" />
<br /><br />
Counter: {{counter}}
</body>
</html>

$digest() - This function iterates through all the watches in the $scope object, and its child $scope objects (if it has any). When $digest() iterates over the watches, it checks if the value of the expression has changed. If the value has changed, AngularJS calls the listener with the new value and the old value.

$digest()

The $digest() function is called whenever AngularJS thinks it is necessary. For example, after a button click, or after an AJAX call. You may have some cases where AngularJS does not call the $digest() function for you. In that case you have to call it yourself.

<html>
<head>
<script src="lib/jquery-1.11.1.js"></script>
<script src="lib/angular.js"></script>
</head> <body ng-app="app">
<div ng-controller="Ctrl">
<button class="digest">Digest my scope!</button>
<br />
<h2>obj value : {{obj.value}}</h2>
</div>
<script>
var app = angular.module('app', []);
app.controller('Ctrl', function ($scope) {
$scope.obj = { value: 1 };
$('.digest').click(function () {
console.log("digest clicked!");
console.log($scope.obj.value++);
//update value
$scope.$digest();
});
});
</script>
</body>
</html>

$apply() - Angular do auto-magically updates only those model changes which are inside AngularJS context. When you do change in any model outside of the Angular context (like browser DOM events, setTimeout, XHR or third party libraries), then you need to inform Angular of the changes by calling $apply() manually. When the $apply() function call finishes AngularJS calls $digest() internally, so all data bindings are updated.

$apply([exp])

Example

<html>
<head>
<title>AngularJS Apply</title>
<script src="lib/angular.js"></script>
<script>
var myapp = angular.module("myapp", []);
var myController = myapp.controller("myController", function ($scope) {
$scope.datetime = new Date();
$scope.updateTime = function () {
$scope.datetime = new Date();
} //outside angular context
document.getElementById("updateTimeButton").addEventListener('click',
function () {
//update the value
$scope.$apply(function () {
console.log("update time clicked");
$scope.datetime = new Date();
console.log($scope.datetime);
});
});
});
</script>
</head>
<body ng-app="myapp" ng-controller="myController">
<button ng-click="updateTime()">Update time - ng-click</button>
<button id="updateTimeButton">Update time</button>
<br />
{{datetime | date:'yyyy-MM-dd HH:mm:ss'}}
</body>
</html>

56.Which one is fast between $digest and $apply?

$digest() is faster than $apply(), since $apply() triggers watchers on the entire scope chain i.e. on the current scope and its parents or children (if it has) while $digest() triggers watchers on the current scope and its children(if it has).

57.Which one handles exception automatically between $digest and $apply?

When error occurs in one of the watchers, $digest() cannot handled errors via $exceptionHandler service, In this case you have to handle exception yourself.

While $apply() uses try catch block internally to handle errors and if error occurs in one of the watchers then it passes errors to $exceptionHandler service.

Pseudo-Code of $apply()

function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}

58.Explain $watch(), $watchgroup() and $watchCollection() functions of scope?

$watch - This function is used to observe changes in a variable on the $scope. It accepts three parameters: expression, listener and equality object, where listener and equality object are optional parameters.

$watch(watchExpression, listener, [objectEquality])

Here, watchExpression is the expression in the scope to watch. This expression is called on every $digest() and returns the value that is being watched.

The listener defines a function that is called when the value of the watchExpression changes to a new value. If the watchExpression is not changed then listener will not be called.

The objectEquality is a boolean type which is used for comparing the objects for equality using angular.equals instead of comparing for reference equality.

scope.name = 'Aarif';
scope.counter = 0;
scope.$watch('name', function (newVal, oldVal) {
scope.counter = scope.counter + 1;
});

$watchgroup - This function is introduced in Angular1.3. This works the same as $watch() function except that the first parameter is an array of expressions to watch.

$watchGroup(watchExpression, listener)

The listener is passed as an array with the new and old values for the watched variables. The listener is called whenever any expression in the watchExpressions array changes.

$scope.teamScore = 0;
$scope.time = 0;
$scope.$watchGroup(['teamScore', 'time'], function(newVal, oldVal) {
if(newVal[0] > 20){
$scope.matchStatus = 'win';
}
else if (newVal[1] > 60){
$scope.matchStatus = 'times up';
});

$watchCollection - This function is used to watch the properties of an object and fires whenever any of the properties change. It takes an object as the first parameter and watches the properties of the object.

$watchCollection(obj, listener)

The listener is called whenever anything within the obj has been changed.

$scope.names = ['Aarif', 'janu', 'sonu', 'monu'];
$scope.dataCount = 4;
$scope.$watchCollection('names', function (newVal, oldVal) {
$scope.dataCount = newVal.length;
});

59.Explain AngularJS scope life-cycle?

Scope data goes through a life cycle when the angular app is loaded into the browser. Understanding the scope life cycle will help you to understand the interaction between scope and other AngularJS components.

The scope data goes through the following life cycle phases:

1. Creation – This phase initialized the scope. The root scope is created by the $injector when the application is bootstrapped. During template linking, some directives create new child scopes.

A digest loop is also created in this phase that interacts with the browser event loop. This digest loop is responsible to update DOM elements with the changes made to the model as well as executing any registered watcher functions.

2. Watcher registration - This phase registers watches for values on the scope that are represented in the template. These watches propagate model changes automatically to the DOM elements.

You can also register your own watch functions on a scope value by using the $watch() function.

3. Model mutation - This phase occurs when data in the scope changes. When you make the changes in your angular app code, the scope function $apply() updates the model and calls the $digest() function to update the DOM elements and registered watches.

When you do the changes to scope inside your angular code like within controllers or services, angular internally call $apply() function for you. But when you do the changes to the scope outside the angular code, you have to call $apply() function explicitly on the scope to force the model and DOM to be updated correctly.

4. Mutation observation – This phase occurs when the $digest() function is executed by the digest loop at the end of $apply() call. When $digest() function executes, it evaluates all watches for model changes. If a value has been changed, $digest() calls the $watch listener and updates the DOM elements.

5. Scope destruction – This phase occurs when child scopes are no longer needed and these scopes are removed from the browser’s memory by using $destroy() function. It is the responsibility of the child scope creator to destroy them via scope.$destroy() API.

This stop propagation of $digest calls into the child scopes and allow the memory to be reclaimed by the browser garbage collector.

60.Explain digest life-cycle in AngularJS?

The digest loop is responsible to update DOM elements with the changes made to the model as well as executing any registered watcher functions.

The $digest loop is fired when the browser receives an event that can be managed by the angular context. This loop is made up of two smaller loops. One processes the $evalAsync queue and the other one processes the $watch list.

The $digest loop keeps iterating until the $evalAsync queue is empty and the $watch list does not detect any changes in the model.

The $evalAsync queue contains those tasks which are scheduled by $evalAsync() function from a directive or controller.

The $watch list contains watches correspondence to each DOM element which is bound to the $scope object. These watches are resolved in the $digest loop through a process called dirty checking. The dirty checking is a process which checks whether a value has changed, if the value has changed, it set the $scope as dirty. If the $scope is dirty, another $digest loop is triggered.

When you do the changes to the scope outside the angular context, you have to call $apply() function explicitly on the scope to trigger $digest cycle immediately.

« Previous | 0 | 1 | 2 | 3 | 4 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com