The largest Interview Solution Library on the web


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

81.What is the difference between $http and $resource?

$http service is a core Angular service which allows you to make AJAX requests by using GET, HEAD, POST, PUT, DELETE, JSONP and PATCH methods.
It is very much like the $.ajax() method in jQuery.
It can be used with RESTful and Non-RESTful server-side data sources.

$http is good for quick retrieval of server-side data that doesn’t really need any specific structure or complex behaviors.

$resource warps $http and allows you to interact with RESTful server-side data sources. It requires the ngResource module to be installed which exist in angular-resource.js

$http is good for retrieval of RESTful server-side data sources that might need any specific structure or complex behaviors.

82.What methods $http service support?

The $http service supports the following methods:

1. $http.get()
2. $http.head()
3. $http.post()
4. $http.put()
5. $http.delete()
6. $http.jsonp()
7. $http.patch()

83.How to enable caching in $http service?

You can enable caching in $http service by setting configuration property cache to true.
When cache is enabled, $http service stores the response from the server in local cache.
In this way, next time the response will be served from the cache without sending request to server.

$http.get("http://server/myserviceapi",{
cache:true
}).success(function(){
//TO DO:
});

84.What methods $resource service object support?

The $resource service object supports the following methods:

1. get()
2. query()
3. save()
4. remove()
5. delete()

85.What is $q service and when to use it?

$q is a service that helps you to run functions asynchronously, and use their return values when they have done processing.

$q service is said to be inspired by Chris Kowal's Q library which allow users to monitor asynchronous progress by providing a "promise" as a return from a call.

It is good when you need to process a number of asynchronous activities simultaneously. The $q.all() function lets you trigger several callbacks at the same time, and use a single then function to join them all together.

var first = $http.get("/app/data/first.json"),
second = $http.get("/app/data/second.json"),
third = $http.get("/app/data/third.json");
$q.all([first, second, third]).then(function (result) {
var tmp = [];
angular.forEach(result, function (response) {
tmp.push(response.data);
});
return tmp; }).then(function (tmpResult) {
$scope.combinedResult = tmpResult.join(", ");
});

86.What is the difference between Kris Kowal's Q and $q?

There are two main differences between Kris Kowal's Q and $q:

1. $q is integrated with the $rootScope.Scope Scope model observation mechanism in angular, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI.
2. Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains all the important functionality needed for common async tasks.

87.What is Restangular?

Restangular is an Angular service specifically designed simply to fetch data from the rest of the world. To use Restangular you need to link the restangular.js file and include restangular resource as a dependency within your angular app.

var app = angular.module('myApp', ['restangular']);
app.controller('MainController',function ($scope, Restangular) {
//TO DO:
});

88.What are the advantages of Rectangular over $resource and $http?

Rectangular has several features that distinguish it from $resource:

1. It uses promises.
2. You can use this in $routeProvider.resolve.
3. It doesn't have all those $resource bugs like trailing slashes, additional: in the URL, escaping information, expecting only arrays for getting lists, etc.

4. It supports all HTTP methods.
5. It supports ETag out of the box.
6. It supports self-linking elements if you receive from the server some item that has a link to itself, you can use that to query the server instead of writing the URL manually.

7. You don't have to create one $resource object per request.
8. You don't have to write or remember ANY URL like $resource. You just write the name of the resource you want to fetch and that's it.
9. It supports nested RESTful resources.
10. Restangular lets you create your own methods.
11. Support for wrapped responses.

89.What is difference between $window and window in AngularJS?

$window is an Angular service which reference to the browser's window object.
The window object is globally available in JavaScript; it causes testability problems, because it is a global variable.
Angular refer to it through the $window service, so that it can be overridden, removed or mocked for testing.

<script>
var app = angular.module('windowExample', []);
app.controller('ExampleController',function ($scope, $window) {
$scope.greeting = 'Hello, World!';
$scope.doGreeting = function (greeting) {
$window.alert(greeting);
};
});
</script>
<div ng-app="windowExample" ng-controller="ExampleController">
<input type="text" ng-model="greeting" />
<button ng-click="doGreeting(greeting)">ALERT</button>
</div>

90.What is difference between $document and window.document in AngularJS?

$document is an Angular service which reference to the browser's window.document object.

<script>
var app = angular.module('documentExample', []);
app.controller('ExampleController', ['$scope', '$document', function ($scope,
$document) {
$scope.title = $document[0].title;
$scope.windowTitle = angular.element(window.document)[0].title;
}]);
</script>
<div ng-app="documentExample" ng-controller="ExampleController">
<p>$document title: <b ng-bind="title"></b></p>
<p>window.document title: <b ng-bind="windowTitle"></b></p>
</div>

91.What is difference between $timeout and window.setTimeout in AngularJS?

$timeout is an Angular service which wraps the browser's window.setTimeout() function into a try/catch block and delegates any exceptions to $exceptionHandler service. It is used to call a JavaScript function after a given time delay. The $timeout service only schedules a single call to the function.

var app = angular.module("app", []);
app.controller("MyController", function ($scope, $timeout) {
$timeout(callAtTimeout, 1000);
});
function callAtTimeout() {
console.log("Timeout occurred");
}

92.What is difference between $interval and window. setInterval in AngularJS?

$interval is an Angular service which wraps the browser's window. setInterval() function.
It is also used to call a JavaScript function repeatedly within a time interval.

var app = angular.module("app", []);
app.controller("MyController", function ($scope, $interval) {
$interval(callAtInterval, 3000);
});
function callAtInterval() {
console.log("Interval occurred");
}

93.What is Routing in AngularJS?

AngularJS Routing helps you to divide your app into multiple views and bind different views to Controllers.
The magic of Routing is taken care by an AngularJS service $routeProvider.
$routeProvider service provides method when() and otherwise() to define the routes for your app.
Routing has dependency on ngRoute module.

Defining Route for your application

<script type="text/javascript">
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/products', { //route
templateUrl: 'views/products.html',
controller: 'productController'
}).
when('/product/:productId', { //route with parameter
templateUrl: 'views/product.html',
controller: 'productController'
}).
otherwise({ //default route
redirectTo: '/index'
});
}]);
</script>

94.What is AngularUI router and how it is different from ngRoute?

The UI-Router is a routing framework for AngularJS built by the AngularUI team.
Unlike ngRoute, it changes your angular app views based on state of the app and not based on the route URL (ngRoute).

The ui-router helps you to create nested views, use multiple views on the same page, have multiple views that control a single view, and more.

To use it you need to include reference of ui-router.js file into your angular app.

95.What is $injector and $inject?

$injector is a service which is used to invoke controller functions, service functions, filter functions, and any other function that might need dependencies as parameters.
Angular creates only a single $injector object when an application is bootstrapped and uses that object for invoking.

<script>
var app = angular.module('app', []);
app.service('s1', function () {
this.value = 22;
});
app.controller("MyCtrl", function ($scope, $injector) {
$scope.doSomething = function () {
var s1 = $injector.get('s1')
s1.value += 10
}
$scope.value = function () {
var s1 = $injector.get('s1')
return s1.value
}
});
</script>
<div ng-app="app" ng-controller="MyCtrl">
<button ng-click="doSomething()">increment</button>
{{value()}}
</div>

$inject is property which is used to inject the dependencies of a function as an array of strings.

<script type="text/javascript">
var MyController = function(renamed$scope, renamedGreeter) {
// ...
}
MyController['$inject'] = ['$scope', 'greeter']; //inject dependencies as an array of
strings
</script>

96.What is Dependency Injection in AngularJS?

Dependency Injection (DI) is a software design pattern that deals with how components get hold of their dependencies.
AngularJS comes with a built-in dependency injection mechanism.
You can divide your AngularJS app into multiple different types of components which AngularJS can inject into each other.

There are following three ways of injecting dependencies into your code:

1. Implicitly from the function parameter names

<script type="text/javascript">
function MyController($scope, greeter) {
// ... }
</script>

2. Using the $inject property annotation

<script type="text/javascript">
var MyController = function(renamed$scope, renamedGreeter) {
// ...
}
MyController['$inject'] = ['$scope', 'greeter'];
</script>

3. Using the inline array annotation

<script type="text/javascript">
someModule.factory('greeter', ['$window', function (renamed$window) {
// ...
}]);
</script>

97.How to do Language Internationalization in AngularJS?

The angular-translate is an AngularJS module that brings i18n (internationalization) and l10n (localization) into your Angular app. It allows you to create a JSON file that represents translation data as per language. These languages specific JSON files can be lazy-loads from the server only when necessary. The angular-translate library (angular-translate.js) also provides built-in directives and filters that make the process of internationalizing simple.

<!DOCTYPE html>
<html>
<head>
<title>AngularJS Internalization</title>
<script src="lib/angular.js"></script>
<script src="lib/angular-translate.js"></script>
<script>
var app = angular.module('myApp', ['pascalprecht.translate']);
app.config(function ($translateProvider) {
$translateProvider.translations('en', {
TITLE: 'Hello',
PARA: 'This is a paragraph.',
BUTTON_LANG_EN: 'english',
BUTTON_LANG_DE: 'german'
})
.translations('de', {
TITLE: 'Hallo',
PARA: 'Dies ist ein Paragraph.',
BUTTON_LANG_EN: 'englisch',
BUTTON_LANG_DE: 'deutsch'
});
//setting default language
$translateProvider.preferredLanguage('en');
});
app.controller('TranslateController', function ($translate, $scope) {
$scope.changeLanguage = function (langKey) {
$translate.use(langKey); };
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="TranslateController">
<h1>{{ 'TITLE' | translate }}</h1>
<p>{{ 'PARA' | translate }}</p>
<button ng-click="changeLanguage('en')" translate="BUTTON_LANG_EN"></button>
<button ng-click="changeLanguage('de')" translate="BUTTON_LANG_DE"></button>
</div>
</body>
</html>

98.What is i18n and L10n?

i18n means Internationalization, where 18 stands for the number of letters in word Internationalization between the first i and last n. It is the process of developing products in such a way that they can be localized for languages and cultures easily.

L10n means Localization, where 10 stand for the number of letters in word Localization between the first L and last n. It is the process of adapting applications and text to enable their usability in a particular culture.

99.What is $locale service?

$locale service provides localization rules for various Angular components. As of now the only public api is: id – {string}

For example, a locale id is formatted as: languageId-countryId (e.g. en-us)

100.What is a locale ID?

A locale is a specific geographical, political, or cultural region. The most commonly used locale ID consists of two parts: language code and country code. For example, en-US, en-AU, hi-IN are all valid locale IDs that have both language codes and country codes.

101.How to manage cookie in AngularJS?

AngularJS provides ngCookies module for reading and writing browser cookies. To use it include the angular-cookies.js file and set ngCookies as a dependency in your angular app. This module provides two services for cookie management: $cookies and $cookieStore.

102.What is difference between $cookies and $cookieStore service?

$cookies - This service provides read/write access to browser's cookies.

If you want to use existing cookie solution, say read/write cookies from your existing server session system then use $cookie.

var app=angular.module('cookiesExample', ['ngCookies']);
app.controller('ExampleController', function ($cookies) {
// Retrieving a cookie
var favoriteCookie = $cookies.myFavorite;
// Setting a cookie $cookies.myFavorite = 'meal';
});

$cookiesStore - $cookieStore is a thin wrapper around $cookies. It provides a key-value (string-object) storage that is backed by session cookies. The objects which are put or retrieved from this storage are automatically serialized or deserialized by angular to JSON and vice versa.

If you are creating a new solution which will persist cookies based on key/value pairs, use $cookieStore.

var app=angular.module('cookieStoreExample', ['ngCookies']);
app.controller('ExampleController',function ($cookieStore) {
// Put cookie
$cookieStore.put('myFavorite', 'meal');
// Get cookie
var favoriteCookie = $cookieStore.get('myFavorite');
// Removing a cookie
$cookieStore.remove('myFavorite');
});

103.How to handle mobile browsers/devices events in AngularJS?

Mobile browsers/devices deal with events differently than desktop browsers. The AngularJS provide ngTouch library (angular-touch.js) to detect mobile browsers/devices events.

For example, Mobile browsers detect a tap event and then wait for second event about 300 ms if any. So if we’re double-tapping the device then after this delay the browser fires a click event.

In this way this delay can make our apps unresponsive. Hence, instead of dealing with the click event, we can detect touch event using ngTouch library. It handles touch detection for us through the ng-click directive. Hence it will take care of calling the correct click event for mobile.

<button ng-click="save()">Save</button>

104.How to detect swipe event in mobile browsers/devices in AngularJS?

The ngTouch library provides swipe directives to capture user swipes, either left or right across the screen. These events are useful when the user want to swipe to the next photo gallery photo or to a new portion of our app.

The ngSwipeLeft directive detects when an HTML element is swiped from the right to the left and the ngSwipeRight directive detects when an HTML element is swiped from the left to the right.

105.How to do animation with the help of AngularJS?

AngularJS 1.2 comes with animation support via ngAnimate module.
To enable animations within your angular app, you need to link the angular-animate.js file and include ngAnimate module as a dependency within your angular app.

106.What directives support animations?

The following directives support animations:

1. ngRepeat – It supports enter, leave and move animations.
2. ngInclude – It supports enter and leave animations.
3. ngView – It supports enter and leave animations.
4. ngIf – It supports enter and leave animations.
5. ngSwitch – It supports enter and leave animations.
6. ngClass – It supports addClass and removeClass animations.
7. ngShow & ngHide – These support addClass and removeClass animations.

107.How to debug AngularJS app in browser?

AngularJS Batarang and ng-inspector are browser extensions for Chrome that adds an inspector pane into browser to debug and understand your AngularJS app. ng-inspector also works with safari browser.

108.How to securely parse and manipulate your HTML data in AngularJS?

AngularJS provides ngSanitize module to securely parse and manipulate HTML data in your application. To use it include the angular-sanitize.js file and set ngSanitize as a dependency in your angular app.

var app = angular.module('sanitizeExample', ['ngSanitize']);
app.controller('ExampleController',function ($scope, $sce) {
var snippet ='<p style="color:blue">an html\n' + '
<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n snippet</p>';
$scope.trustedSnippet = $sce.trustAsHtml(snippet); //sce=Strict Contextual Escaping
});

The snippet may contain HTML, CSS, URLs and JavaScript code which you want to safely render in your app.

109.What is Angular 2.0?

Angular 2.0 is being written with AtScript, but that doesn't mean you have to write your application code with AtScript or know anything about AtScript to use Angular 2.0.
You can easily write with TypeScript, ES6, ES5, CoffeeScript etc. whatever you like.
It is still in development phase (at the time of writing this book).

110.What is AtScript?

AtScript is Google’s new superset for JavaScript.
It enhances JavaScript with new features to make it more robust.
It is not only designed to run on top of ECMAScript 5 and ECMAScript 6, but on the top of Microsoft’s superset TypeScript language as well.
The aim of AtScript is to make type annotation data available at runtime to enhance JavaScript with type,field and metadata annotations.

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


copyright © 2014 - all rights riserved by javatechnologycenter.com