Thursday, 12 May 2016

Javascript InteviewQuestions


1).what are new features in html5?

HTML 5 features which are useful right now include:

Web Workers: Certain web applications use heavy scripts to perform functions. Web Workers

use separate background threads for processing and it does not effect the performance of a web

page.

Video: You can embed video without third­party proprietary plug­ins or codec. Video becomes as

easy as embedding an image.

Canvas: This feature allows a web developer to render graphics on the fly. As with video, there is

no need for a plug in.

Application caches: Web pages will start storing more and more information locally on the

visitor's computer. It works like cookies, but where cookies are small, the new feature allows for

much larger files. Google Gears is an excellent example of this in action.

Geolocation: Best known for use on mobile devices, geolocation is coming with HTML5.

2).What are semantic elements?

A semantic element clearly describes its meaning to both the browser and the developer.

Examples of non­semantic elements: <div> and <span> ­ Tells nothing about its content.

Examples of semantic elements: <form>, <table>, and <img> ­ Clearly defines its content.

3).What do you mean by session storage in HTML5?

The sessionStorage stores the data for only one session. The data is deleted when the

user closes the specific browser tab.

Eg: sessionStorage.clickcount = 1;

4)What is Geolocation API in HTML?

The geolocation API allows the user to provide their location to web applications if they so

desire. For privacy reasons, the user is asked for permission to report location

information.

5).So how do we implement application cache in HTML 5 ?

HTML5 provides an application caching mechanism that lets web­based applications run

offline. Developers can use the Application Cache (AppCache) interface to specify

resources that the browser should cache and make available to offline users. Applications

that are cached load and work correctly even if users click the refresh button when they

are offline.

Using an application cache gives an application the following benefits:

Offline browsing: users can navigate a site even when they are offline.

Speed: cached resources are local, and therefore load faster.

Reduced server load: the browser only downloads resources that have changed from

the server.

Enabling the application cache:

To enable the application cache for an application, you must include the manifest attribute

in the <html> element in your application's pages, as shown in the following example:

<html manifest="example.appcache">

...

</html>

6).What are Web Workers?

A web worker is a JavaScript that runs in the background, independently of other scripts,

without affecting the performance of the page. You can continue to do whatever you want:

clicking, selecting things, etc., while the web worker runs in the background.

7).What do you mean by local storage in HTML5?

The localStorage object stores the data with no expiration date. The data will not be

deleted when the browser is closed, and will be available the next day, week, or year.

// Store

localStorage.setItem("lastname", "Smith");

// Retrieve

document.getElementById("result").innerHTML = localStorage.getItem("lastname");

The syntax for removing the "lastname" localStorage item is as follows:

localStorage.removeItem("lastname");

8). What are the drawbacks of cookies?

∙ The cookies are enabled and if any other user tries to access the cookies he can

easily view what the previous user had accessed.If its some sensitive data, it can

be a major security threat.

∙ Fundamental disadvantage is as per the definition it cannot send the huge amount

of data.

∙ More amount of data will be transferred between the browser and server.

∙ In case of some browser softwares we have a option to disable cookies,for

example in case NetscapeCommunicator we have a option to disable cookies,in

such cases our application fails.

CSS

1). What are new features in css3?

CSS Animations and Transitions.

Advanced Selectors (eg: p::first­letter,p::first­line etc).

Generated Content and Counters.

Gradients.

Webfonts.

Box Sizing.

Border Images.

Multiple Backgrounds.

CSS 3D Transforms.

2). What is the purpose of the z­index and how is it used?

The z­index property specifies the stack order of an element.

An element with greater stack order is always in front of an element with a lower stack

order.

z­index only works on positioned elements (position:absolute, position:relative, or

position:fixed).

CSS SYNTAX : z­index: auto|number|initial|inherit;

3).What is Pseudo­elements ?

A CSS pseudo­element is used to style specified parts of an element. For example, it can

be used to: Style the first letter, or line, of an element. Insert content before, or after, the

content of an element.

Example:

p::first­line {

color: #ff0000;

font­variant: small­caps;

Above css will be applied only to the first line of paragraph.

4). What are the possible values of the "Position" attributes?

The position property specifies the type of positioning method used for an element.

There are four different position values:

∙ static

∙ relative

∙ fixed

∙ absolute

5).What is The Viewport?

The viewport is the user's visible area of a web page.

The viewport varies with the device, and will be smaller on a mobile phone than on a

computer screen.

Before tablets and mobile phones, web pages were designed only for computer screens,

and it was common for web pages to have a static design and a fixed size.

Then, when we started surfing the internet using tablets and mobile phones, fixed size

web pages were too large to fit the viewport. To fix this, browsers on those devices scaled

down the entire web page to fit the screen.

Eg: <meta name="viewport" content="width=device­width, initial­scale=1.0">

6). What is a Media Query?

Media query is a CSS technique introduced in CSS3.

It uses the @media rule to include a block of CSS properties only if a certain condition is

true.

Example:

If the browser window is smaller than 500px, the background color will change to

lightblue:

@media only screen and (max­width: 500px) {

body {

background­color: lightblue;

}

7). media queries break points?

we made a web page with rows and columns, and it was responsive, but it did not look

good on a small screen.

Media queries can help with that. We can add a breakpoint where certain parts of the

design will behave differently on each side of the breakpoint.

/* Smartphones (portrait and landscape) ­­­­­­­­­­­ */

@media only screen and (min­device­width : 320px) and (max­device­width : 480px) {

/* Styles */

/* iPads (portrait and landscape) ­­­­­­­­­­­ */

@media only screen and (min­device­width : 768px) and (max­device­width : 1024px) {

/* Styles */

@media only screen and (min­device­width : 768px) and (max­device­width : 1024px)

and (orientation : portrait) and (­webkit­min­device­pixel­ratio : 2) {

/* Styles */

/* Desktops and laptops ­­­­­­­­­­­ */

@media only screen and (min­width : 1224px) {

/* Styles */

8). What are pseudo classes?

A pseudo­class is used to define a special state of an element.

For example, it can be used to:

∙ Style an element when a user mouses over it

∙ Style visited and unvisited links differently

∙ Style an element when it gets focus

9). What are the differences between inline, block and inline­block?

inline, elements do not break the flow. think of span it fits in the line. Important points

about inline elements, margin/ padding will push other elements horizontally not vertically.

Moreover, inline elements ignores height and width.

block, breaks the flow and dont sits inline. they are usually container like div, section, ul

and also text p, h1, etc.

inline­block, will be similar to inline and will go with the flow of the page. Only differences

is this this will take height and width.

10). What do you know about transition,CSS3 animations?

Transition allows to add an effect while changing from one style to another. You can set

the which property you want to transition, duration, how you want to transit (linear, ease,

ease­in, ease­out, cubic­bezier) and delay when transition will start. you can transition

more than one property by comma separation.

CSS Animations is a module of CSS that defines how to animate the values of CSS

properties over time, using keyframes. The behavior of these keyframe animations can be

controlled by specifying their duration, their number of repetitions, and how they repeat.

11).The Difference Between Block and Inline?

Inline:

­ respect left & right margins and padding, but not top & bottom

­ cannot have a width and height set

­ allow other elements to sit to their left and right.

Block:

­ respect all of those

­ force a line break after the block element

13).How to avoid cross browser issues?(browser compatablility)?

1. Prefix css3 styles

­moz­ /* Firefox and other browsers using Mozilla's browser engine */

­webkit­ /* Safari, Chrome and browsers using the Webkit engine */

­o­ /* Opera */

­ms­ /* Internet Explorer (but not always) */

2. Use a reset

nav,output,ruby,section,summary,time,mark,audio,video {

border: 0;

margin: 0;

padding: 0;

vertical­align: baseline;

}

3. Avoid padding with widths

When you add padding to an element with a width, it will end up much larger than what it

should be. The width and the padding will be added together. So, if I have an element with

the width of 100px, and I add a padding of 10px to that same element, then the awkward

browser behavior will make that element 120px.

To fix that, add this to everything that you do from now on:

* { ­webkit­box­sizing: border­box; /* Safari/Chrome, other WebKit */

­moz­box­sizing: border­box; /* Firefox, other Gecko */

box­sizing: border­box; }

4. Clear your floats, always!

Make sure you clear your floats! If you don’t clear your floats, things will start

acting weird. To learn more about how floats act on browsers, check out this

article from Chris Coyier.

To clear your floats, use this snippet of CSS:

.parent­selector:after {

content: "";

display: table;

clear: both;

}

5. Test it out!

Use VM Ware, browsershots, or just DL the browsers and check them out to make sure

they work!

JAVASCRIPT

1).Explain the difference between “==” and “===”?

== attempts to convert the values to the same type before testing if they're the same. "5"

== 5

=== does not do this; it requires objects to be of the same type to be equal. "5" !== 5

2).How to define a anonymous function?

An anonymous function is a function that was declared without any named identifier to

refer to it. As such, an anonymous function is usually not accessible after its initial

creation.

Ex: var anon = function() {

};

anon();

3). what are datatypes in javascript?What are the two basic groups of

dataypes in JavaScript?

In JavaScript, there are two data types, Primitive Data Types Primitive Data Types.

Primitive Data Types:

String

Number

Boolean

Null

alert('I am anonymous');

Undefined

Non­Primitive Data Types:

Object

Array

4).What do mean by NULL in Javascript?

The value null represents the intentional absence of any object value. It is one of

JavaScript's primitive values.

Ex: var x = null;

5). What is an undefined value in JavaScript?

The undefined property indicates that a variable has not been assigned a value.

var x;

if (typeof x === 'undefined') {

// these statements execute

6).What is a “closure” in JavaScript? Provide an example

A closure is much like an object. It gets instantiated whenever you call a function. The

scope of a closure in JavaScript is lexical, which means that everything that is contained

within the function the closure belongs to, has access to any variable that is in it.

Lexical Scoping:

function init() {

var name = "Mozilla"; // name is a local variable created by init

function displayName() { // displayName() is the inner function, a closure

}

displayName();

}

init();

7).What is Hoisting in javascript?

Hoisting is JavaScript's default behavior of moving declarations to the top.

Ex 1:

var myvar = 'my value';

(function() {

alert(myvar); // my value

})();

Ex 2:

var myvar = 'my value';

(function() {

alert(myvar); // undefined

var myvar = 'local value';

})();

Within its current scope, regardless of where a variable is declared, it will be, behind the

scenes, hoisted to the top. However, only the declaration will be hoisted. If the variable is

alert(name); // use variable declared in the parent function

also initialized, the current value, at the top of the scope, will initially be set to undefined.












22down vote
Two-way binding means that any data-related changes affecting the model are immediately propagated to the matching view(s), and that any changes made in the view(s) (say, by the user) areimmediately reflected in the underlying model. When app data changes, so does the UI, and conversely.

3)Explain what is DI (Dependency Injection ) and how an object or function can get a hold of its dependencies?
One of the features that I really like in AngularJS is its use of dependency injection across the framework
What is Dependency Injection?
Dependency Injection is a software design pattern in which an object is given its dependencies, rather than the object creating them itself. It is about removing the hard-coded dependencies and making it possible to change them whenever needed.
Why do you need to inject dependencies?
  • Separate the process of creation and consumption of dependencies
  • Let the consumer worry only about how to use the dependency, and leave the process of creation of the dependency to somebody else
  • Allow concurrent/independent development of the dependency and the dependent entity, while only maintaing a known contract
  • Facilitate changing of the dependencies when needed
  • Allow injecting mock objects as dependencies for testing, by maintaining the agreed contract
How does dependency injection work in Angular?
Angular leverages dependency injection all across the framework. It works with functions defined for controller, directive, service, factory, etc.
Ex::
var app = angular.module("DemoApp", []);
// Controller is injected with $scope and $http as dependencies
app.controller("DemoController", function ($scope, $http) {
   $http.get('https://api.github.com/users/angular/repos').success(function (repos) {
       $scope.repos = repos
   });
});
AngularJS has a built-in dependency injector that keeps track of all components (services, values, etc.) and returns instances of needed components using dependency injection. Angular’s dependency injector works based on names of the components.
A simple case of dependency injection:
myModule.controller("MyController", function($scope, $window, myService){
});
Here, $scope, $window and myService are passed into the controller through dependency injection. But the above code will break when the code is minified. Following approach solves it:
myModule.controller("MyController", ["$scope", "$window", "myService",
   function($scope, $window, myService){
}]);


4)What is the difference between Factory ,Service and Provider?

When either or are injected into a controller, they will both have a method that returns "HelloWorld". The service constructor function is instantiated once at declaration and the factory object ispassed around every time it is injected, but there is still just one instance of the factory. All are singletons.

Factories offer slightly more flexibility than services because they can return functions which canthen be 'd. This follows the factory pattern from object oriented programming. A factory can be an object for creating other objects.

Syantax:
app.service('helloWorldService', function(){
this.hello = function() {

return "Hello World";};
});

app.factory('helloWorldFactory', function(){
return {hello: function() {
return "Hello World";
}}
});
A provider is a low level recipe. The $get() method of the provider is registered as a factory. Providers are available to config blocks and other providers. Once application configuration phase is completed, access to providers is prevented.
After the configuration phase, the $get() method of the providers are executed and they are available as factories. Services, Factories and values are wrapped inside provider with $get() method returning the actual logic implemented inside the provider.

angular.module("myModule").provider("samplePrd", function(){
   this.initCities = function(){
       console.log("Initializing Cities…");
   };
 
   this.$get = function(){
       var cities = ["New Delhi", "Mumbai", "Kolkata", "Chennai"];
       function addCity(city){
           cities.push(city);
       }
       function getCities(){
           return cities;
       }
       return{
           getCities: getCities,
           addCity:addCity
       };
   }
});


5)Difference between $scope and $rootScope?What is “$rootScope” and how is it related with “$scope”?
scope is an object that refers to the application model. It acts as a context for evaluating expressions. Typically, it acts as a glue between controller and view. Scopes are hierarchical in nature and follow the DOM structure of your angular app. AngularJS has two scope objects: $rootScope and $scope. Let's have a look, how they work.
$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 viewmodel 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.
Ex:
<!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>

Use:
When you use ng-model with $rootScope objects then AngularJS updates those objects under a specific $scope of a controller but not at global level $rootScope.
  1. Create a private $scope for each controller to bind it to the view.
  2. Create a private $scope for each controller to bind it to the view.
6)       What are controllers and need of ng-controller and ng-model in Angular?
“Controllers” are simple javascript function which provides data and logic to HTML UI. As the name says controller they control how data flows from the server to HTML UI.
For example below is simple “Customer” controller which provides data via “CustomerName” and “CustomerCode” property and Add/ Update logic to save the data to database.
function Customer($scope)
{
       $scope.CustomerName = "Shiv";
       $scope.CustomerCode = "1001";
       $scope.Add = function () {
       }
       $scope.Update = function () {
       }
}
“ng-controller” is a directive.Controllers are attached to the HTML UI by using the “ng-controller” directive tag and the properties of the controller are attached by using “ng-model” directive. For example below is a simple HTML UI which is attached to the “Customer” controller via the “ng-controller” directive and the properties are binded using “ng-model” directive.
<form ng-controller="Customer">       
<input type=text id="CustomerName"  ng-model="CustomerName"/>       
<input type=text id="CustomerCode"  ng-model="CustomerCode"/>
</form>

7) what are directives?What are the different types of Directive?
AngularJS directives are what controls the rendering of the HTML inside an AngularJS application.
Examples of directives are the interpolation directive ( {{ }} ), the ng-repeat directive
and ng-if directive.

It is possible to implement your own directives too. This is what AngularJS refers to as "teaching HTML new tricks".
This text will show you how to do that.
Directive Types
You can implement the following types of directives:
Element directives
Attribute directives
CSS class directives
Comment directives
A Basic Directive
You register a directive with a module. Here is an example of how that looks:

myapp = angular.module("myapp", []);

myapp.directive('div', function() {
   var directive = {};

   directive.restrict = 'E'; /* restrict this directive to elements */

   directive.template = "My first directive: {{textToInsert}}";

   return directive;
});

8)Explain what is the difference between link and compile in Angular.js?

Compiler is an angular service which traverses the DOM looking for attributes.
The compilation process happens into two phases.

Compile: traverse the DOM and collect all of the directives.
The result is a linking function.
Link: combine the directives with a scope and produce 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. Making the scope model a single source of truth.


what is filters?what is the default filter for currency?

Filters are used to extend the behavior of binding expressions and directives.
In general, they are used to format values or to apply certain conditions.
They are executed whenever the value bound in the binding expression is updated.

angular.module("myModule").filter("dollarToRupeee", function(){
   return function(val){
       return "Rs. " + val * 60;
   };
});

Usage:

<span>{{price | dollarToRupee}}</span>
Config block:
angular.module("myModule").config(function(samplePrdProvider, sampleConstant){
   samplePrdProvider.init();
   console.log(sampleConstant.pi);
});
Config block runs as soon as a module is loaded. As the name itself suggests, the config block is used to configure the application. Services, Factories and values are not available for config block as they are not created by this time. Only providers and constants are accessible inside the config block. Config block is executed only once in the lifetime of an Angular application.
Run block:
angular.module("myModule").run(function(<any factories="">){ console.log("Application is configured. Now inside run block"); });  </any>
Run block is used to initialize certain values for further use, register global events and anything that needs to run at the beginning of the application. Run block is executed after config block and it gets access to services, values and factories. Run block is executed only once in the lifetime of an Angular application.

Directives :

Directives add the capability of extending HTML. They are the most complex and the most important part of AngularJS. A directive is a function that returns a special object, generally termed as Directive Definition Object. The Directive Definition Object is composed of several options as shown in the above snippet. Following is a brief note on them:

restrict: Used to specify how a directive can be used. Possible values are: E (element), A (Attribute), C (Class) and M (Comment). Default value is A
template: HTML template to be rendered in the directive
templateUrl: URL of the file containing HTML template of the element
replace: Boolean value denoting if the directive element is to be replaced by the template. Default value is false
transclude: Boolean value that says if the directive should preserve the HTML specified inside directive element after rendering. Default is false
scope: Scope of the directive. It may be same as the scope of surrounding element (default or when set to false), inherited from scope of the surrounding element (set to true) or an isolated scope (set to {})
require: A list of directive that the current directive needs. Current directive gets access to controller of the required directive. An object of the controller is passed into link function of the current directive
controller: Controller for the directive. Can be used to manipulate values on scope or as an API for the current directive or a directive requiring the current directive
priority: Sets priority of a directive. Default value is 0. Directive with higher priority value is executed before a directive with lower priority
terminal: Used with priority. If set to true, it stops execution of directives with lower priority. Default is false
link: A function that contains core logic of the directive. It is executed after the directive is compiled. Gets access to scope, element on which the directive is applied (jqLite object), attributes of the element containing the directive and controller object. Generally used to perform DOM manipulation and handling events
compile: A function that runs before the directive is compiled. Doesn’t have access to scope as the scope is not created yet. Gets an object of the element and attributes. Used to perform DOM of the directive before the templates are compiled and before the directive is transcluded. It returns an object with two link functions:
pre link: Similar to the link function, but it is executed before the directive is compiled. By this time, transclusion is applied
post link: Same as link function mentioned above


myModule.directive("directiveName", function (injectables) {
   return {
       restrict: "A",
       template: "<div> </div>",
       templateUrl: "directive.html",
       replace: false,
       transclude: false,
       scope: false,
       require: ["someOtherDirective"],
       controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
       link: function postLink(scope, iElement, iAttrs) { ... },
       priority: 0,
       terminal: false,
       compile: function compile(tElement, tAttrs, transclude) {
           return {
               pre: function preLink(scope, iElement, iAttrs, controller) { ... },
               post: function postLink(scope, iElement, iAttrs, controller) { ... }
           }
       }
   };
});

Most used built-in directives:

ng-app: To bootstrap the application
ng-controller: To set a controller on a view
ng-view: Indicates the portion of the page to be updated when route changes
ng-show / ng-hide: Shows/hides the content within the directive based on boolean equivalent of value assigned
ng-if: Places or removes the DOM elements under this directive based on boolean equivalent of value assigned
ng-model: Enables two-way data binding on any input controls and sends validity of data in the input control to the enclosing form
ng-class: Provides an option to assign value of a model to CSS, conditionally apply styles and use multiple models for CSS declaratively
ng-repeat: Loops through a list of items and copies the HTML for every record in the collection
ng-options: Used with HTML select element to render options based on data in a collection
ng-href: Assigns a model as hyperlink to an anchor element
ng-src: Assigns a model to source of an image element
ng-click: To handle click event on any element
ng-change: Requires ng-model to be present along with it. Calls the event handler or evaluates the assigned expression when there is a change to value of the model
ng-form: Works same as HTML form and allows nesting of forms
ng-non-bindable: Prevents AngularJS from compiling or binding the contents of the current DOM element
ng-repeat-start and ng-repeat-end: Repeats top-level attributes
ng-include: Loads a partial view
ng-init: Used to evaluate an expression in the current scope
ng-switch conditionally displays elements
ng-cloak to prevent Angular HTML to load before bindings are applied

Routes:

Routes in AngularJS application are defined using $routeProvider. We can define a list of routes and set one of the routes as default using otherwise() method; this route will respond when the URL pattern doesn’t match any of the configured patterns.

Registering routes:

myModule.config(function($routeProvider){
   $routeProvider.when("/home", {templateUrl:"templates/home.html",
                                 controller: "HomeController"}).when("/details/:id", {template: "templates/details.html",                                       controller:"ListController"})
               .otherwise({redirectTo: "/home"});
});
Some useful utility functions

angular.copy - Creates a deep copy of source
angular.extend - Copy methods and properties from one object to another
angular.element - Wraps a raw DOM element or HTML string as a jQuery element
angular.equals - Determines if two objects or two values are equivalent
angular.forEach - Enumerate the content of a collection
angular.toJson - Serializes input into a JSON-formatted string
angular.fromJson - Deserializes a JSON string
angular.identity - Returns its first argument
angular.isArray - Determines if a reference is an Array
angular.isDate - Determines if a value is a date
angular.isDefined - Determines if a reference is defined
angular.isElement - Determines if a reference is a DOM element
angular.isFunction - Determines if a reference is a Function
angular.isNumber - Determines if a reference is a Number
angular.isObject - Determines if a reference is an Object
angular.isString - Determines if a reference is a String
angular.isUndefined - Determines if a reference is undefined
angular.lowercase - Converts the specified string to lowercase
angular.uppercase - Converts the specified string to uppercase

$http:

$http is Angular’s wrapper around XmlHttpRequest. It provides a set of high level APIs and a low level API to talk to REST services. Each of the API methods return $q promise object. Following are the APIs exposed by $http:

$http.$get(url): Sends an HTTP GET request to the URL specified
$http.post(url, dataToBePosted): Sends an HTTP POST request to the URL specified
$http.put(url, data): Sends an HTTP PUT request to the URL specified
$http.patch(url, data): Sends an HTTP PATCH request to the URL specified
$http.delete(url): Sends an HTTP DELETE request to the URL specified
$http(config): It is the low level API. Can be used to send any of the above request types and we can also specify other properties to the request. Following are the most frequently used config options:
method: HTTP method as a string, e.g., ‘GET’, ‘POST’, ‘PUT’, etc.
url: Request URL
data: Data to be sent along with request
headers: Header parameters to be sent along with the request
cache: caches the response when set to true
Following is a small snippet showing usage of $http:

$http.get('/api/data').then(function(result){
   return result.data;
}, function(error){
   return error;
});

what is unit testing?
AngularJS is built with unit testing in mind. Every component defined in Angular is testable. Dependency injection is the key factor behind it. Take any kind of component in Angular, it can’t be written without getting some of the external components injected in. This gives freedom to programmers to pass any object of their choice instead of the actual component object while writing tests. The only thing to be taken care is to create an object with the same shim as the component.

AngularJS code can be unit tested using any JavaScript Unit Testing framework like QUnit, Jasmine, Mocha or any other framework. Jasmine is the most widely used testing framework with Angular. Tests can be run anywhere, in browser or even in console using Karma test runner.

The main difference between application code and unit tests is, application code is backed by the framework and browser, whereas unit tests are totally under our control. So, wherever we get objects automatically injected or created by AngularJS, these objects are not available in unit tests. They have to be created manually.

$compile

Used to compile templates after the compilation phase. $compile is generally used in link function of directives or services. But, it should be used with caution as manual compilation is an expensive operation.

myModule.directive('sampleDirective', function(){
   return {
       link: function(scope, elem, attrs){
           var compiled = $compile('<div>{{person.name}}</div>')(scope);
           elem.html(compiled);
       }
   };
});

Services: If you need to share state across your application, or need a solution for data storage or cache, think of Services. Services are singletons and can be used by other components such as directives, controllers, filters and even other services. Services do not have a scope of their own, so it is permissible to add eventlisteners in Services using $rootScope.

Deferred and Promise - The $q service provides deferred objects/promises.

$q.all([array of promises]) - creates a Deferred object that is resolved when all of the input promises in the specified array are resolved in future
$q.defer() - creates a deferred object with a promise property that can be passed around applications, especially in scenarios where we are integrating with a 3rd-party library
$q.reject(reason) - Creates a promise that is resolved as rejected with the specified reason. The return value ensures that the promise continues to the next error handler instead of a success handler.
deferredObject.resolve - Resolves the derived promise with the value
deferredObject.reject - Rejects the derived promise with the reason and triggers the failure handler in the promise.



// Define the Person constructor
var Person = function(firstName) {
  this.firstName = firstName;
};

// Add a couple of methods to Person.prototype
Person.prototype.walk = function(){
  console.log("I am walking!");
};

Person.prototype.sayHello = function(){
  console.log("Hello, I'm " + this.firstName);
};

// Define the Student constructor
function Student(firstName, subject) {
  // Call the parent constructor, making sure (using call)
  // that "this" is set correctly during the call
  Person.call(this, firstName);

  // Initialize our Student-specific properties
  this.subject = subject;
}

// Create a Student.prototype object that inherits from Person.prototype.
// Note: A common error here is to use "new Person()" to create the
// Student.prototype. That's incorrect for several reasons, not least 
// that we don't have anything to give Person for the "firstName" 
// argument. The correct place to call Person is above, where we call 
// it from Student.
Student.prototype = Object.create(Person.prototype); // See note below

// Set the "constructor" property to refer to Student
Student.prototype.constructor = Student;

// Replace the "sayHello" method
Student.prototype.sayHello = function(){
  console.log("Hello, I'm " + this.firstName + ". I'm studying "
              + this.subject + ".");
};

// Add a "sayGoodBye" method
Student.prototype.sayGoodBye = function(){
  console.log("Goodbye!");
};

// Example usage:
var student1 = new Student("Janet", "Applied Physics");
student1.sayHello();   // "Hello, I'm Janet. I'm studying Applied Physics."
student1.walk();       // "I am walking!"
student1.sayGoodBye(); // "Goodbye!"

// Check that instanceof works correctly
console.log(student1 instanceof Person);  // true 
console.log(student1 instanceof Student); // true











No comments:

Post a Comment