Angularjs Interview Questions and Answers Set 9

81.What Are Different Ways To Create Service In AngularJS?

There are 5 different ways to create services in AngularJS.

Value

Factory

Service

Provider

Constant

 

Let’s discuss, each of the above AngularJS service types one by one with code example:

  1. AngularJS Value.

It is the simplest service type supported by AngularJS that we can create and use. It is similar to a key-value pair or like a variable having a value. It can store only a single value. Let’s take an example and create a service that displays username:

var app=angular.module(“app”,[]);app.value(“username”,”Madhav”);Code to use “Value”:

We can use this service anywhere by using dependency injection. Following example injects the service in a controller:

app.controller(“MainController”,function($scope, username){$scope.username=username;});

In the above example, we have created a Value service “username” and used it in MainController.

  1. AngularJS Factory.

Value service may be very easy to write but, it lacks many important features. So, the next service type we will look at is “Factory” service. After its creation, we can even inject other services into it. Unlike Value service, we cannot add any dependency in it.

Let’s take an example to create a Factory service.

app.factory(“username”,function(){var name=”John”;return {name:name}});

The above code shows that Factory service takes “function” as an argument. We can inject any number of dependencies or methods in this “function” as required by this service. This function must return some object. In our example, it returns an object with the property name. Now, let us look, as to how we can use this service:

Code to use “Factory”:

The function returns an object from service which has a property name so we can access it and use it anywhere. Let’s see how we can use it in the controller:

app.controller(“MainController”,function($scope, username){$scope.username=username.name;});

We are assigning the username from factory service to our scope username.

  1. AngularJS Service.

It works same as the “Factory” service. But, instead of a function, it receives a Javascript class or a constructor function as an argument. Let’s take an example. Suppose we have a function:

function MyExample(num){this.variable=”value”;}

Now, we want to convert the function into a service. Let’s take a look at how we can do this with “Factory” method:

app.factory(“MyExampleService”,[“num” ,function(num){return new MyExample(num);}]);

Thus in this way, we will create its new instance and return it. Also, we have injected <num> as a dependency in Factory service. Now, let’s see how we can do this using Service type:

app.service(“MyExampleService”,[“num”, MyExample]);

Thus, we have called the service method on the module and provided its name, dependency, and the name of the function in an array.

  1. AngularJS Provider.

It is the parent of all the service types supported by AngularJS, except the “Constant” that we will discuss in the next section. It is the core of all the service types. Thus we can say that other services work on top of it. It allows us to create a configurable service that must implement the <$get> method.

We use this service to expose the API that is responsible for doing the application-wide configuration. The configuration should complete before starting the application.

Let’s take an example.

app.provider(‘authentication’, function() {
var username = “John”;
return {       set: function(newUserName) {           username = newUserName;       },
$get: function() {
function getUserName()
{
return username;
}
return {               getUserName: getUserName           };
}
};});

This example initializes a provider with its name as “authentication”. It also implements a <$get> function, which returns a method “getUsername” which in turn returns the private variable called username. This also has a setter, using it we can set the username on application startup as follows:

app.config([“authenticationProvider”, function(authenticationProvider) {   authenticationProvider.set(“Mihir”);}]);

  1. AngularJS Constant.

As the name suggests, this service helps us to declare constants in our application. We can then use them wherever needed, just by adding it as a dependency. There are many places, where we use constants like some base URLs, application name, etc.

We just define them once and use them anywhere as per our need. Thus, this technique allows us to write the definition at one place. If there is any change in the value later, we have to do the modifications at one place only.

Here is an example of how we can create constants:

app.constant(‘applicationName’, ‘Service Tutorials’);

82.List out the differences between config and run methods in AngularJS?

Config Block – Constants and providers can be injected into config blocks and this block can be created using config method.

Run Block – Run block will be executed after config block. Run block is used to inject constants and instances and this block can be created using run method.

Eg :

angular.module(‘myTestModule’, []).
config(function (injectables) {
// config block
}).
run(function (injectables) {
// run block
});

83.How Would You Use An Angular Service To Pass Data Between Controllers? Explain With Examples?

Using a service is the best practice in Angular to share data between controllers. Here is a step by step example to demonstrate data transfer.

We can prepare the data service provider in the following manner.

app.service(‘dataService’, function() {
var dataSet = [];
var addData = function(newData) {
dataSet.push(newData);
};
var getData = function(){
return dataSet;
};
return {    addData: addData,    getData: getData  };
});

Now, we’ll inject the service dependency into the controllers.

Say, we have two controllers – pushController and popController.

The first one will add data by using the data service provider’s addData method. And the latter will fetch this data using the service provider’s getData method.

 

app.controller(‘pushController’, function($scope, dataService) {
$scope.callToAddToProductList = function(currObj){        dataService.addData(currObj);
};});

app.controller(‘popController’, function($scope, dataService) {
$scope.dataSet = dataService.getData();
});

84.Mention what are the styling form that ngModel adds to CSS classes?

ngModel adds these CSS classes to allow styling of form as well as control:

ng- valid

ng- invalid

ng-pristine

ng-dirty

85.What are animating elements in AngularJS?

ng-repeat enter, leave, move
ng-view enter, leave
ng-include enter, leave
ng-switch enter, leave
ng-if enter, leave
ng-class add, remove
ng-show add, remove
ng-hide add, remove

86.Explain RouteProvider in AngularJS?

$routeProvider is the key service which set the configuration of URLs, map them with the corresponding HTML page or ng-template, and attach a controller with the same.

Let’s see the following example:

var mainApp = angular.module(“mainApp”, [‘ngRoute’]);
mainApp.config([‘$routeProvider’, function($routeProvider) {
$routeProvider.when(‘/addEmployee’, {      templateUrl: ‘addEmployee.htm’, controller: ‘AddEmployeeController’   })
.otherwise({redirectTo: ‘/addEmployee’});}]);

Following are the important points to be considered in above example.

routeProvider is defined as a function under config of the mainApp module using a key as ‘$routeProvider’.

$routeProvider.when defines a URL “/addEmployee” which is then mapped to “addEmployee.htm”. This <addEmployee.htm> should be present in the same path as main HTML page.

“otherwise” is used to set the default view.

“controller” is used to set the corresponding controller for the view.

87.Explain what Angular JS routes does ?

Angular js 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 Angular.js is called a route.

A value in Angular JS is a simple object. It can be a number, string or JavaScript object. Values are typically used as configuration injected into factories, services or controllers. A value should be belong to an Angular.js module.

Injecting a value into an Angular.js controller function is done by adding a parameter with the same name as the value

88.Explain how routing works in AngularJS?

Routing enables to create different URL for different content in our application. Different content for different URL enables to bookmark the URL of specific content and this is called route and this mechanism is called routing.

89.What Is Ng-View In AngularJS?

The ng-view tag creates a placeholder where an HTML or ng-template view can be placed based on the configuration.

Let’s take an example.

<div ng-app = “testApp”>    <div ng-view>    <!– Target Html Template here –>    </div></div>

In other words, ng-view is the directive that works as a container for angularJS to switch between views.

90.How to make Http get request from AngularJS with an example?

From AngularJS we can use “$http” service. Below is the sample code for http get request –

$http.get(‘/MyURL’).
success(function(data, status, headers, config) {
// code here
}).
error(function(data, status, headers, config) {
// code here
});