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. 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() 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.
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.
<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:
<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
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.
<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.
<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: 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.
<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. 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.
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. 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. |