Interview Questions.

AngularJS Interview Questions and Answers

fluid

AngularJS Interview Questions and Answers

Q1.What is AngularJS?

Ans: AngularJS is a javascript framework used for creating single net page programs.  It allows you to apply HTML as your template language and permits you to increase HTML’s syntax to specific your application’s additives simply

Q2. Explain what are the important thing features of AngularJS ?

Ans: The key capabilities of AngularJS are

Scope

Controller

Model

View

Services

Data Binding

Directives

Filters

Testable

Q3. Explain what's scope in AngularJS ?

Ans: Scope refers back to the application version, it acts like glue among utility controller and the view.  Scopes are organized in hierarchical structure and impersonate the DOM ( Document Object Model) shape of the application.  It can watch expressions and propagate activities.

Q4. Explain what's services in AngularJS ?

Ans: In AngularJS offerings are the singleton gadgets or capabilities which might be used for carrying out unique duties.  It holds a few business common sense and these function can be called as controllers, directive, filters and so forth.

Q5.Explain what's Angular Expression? Explain what is key difference between angular expressions and JavaScript expressions?

Ans: Like JavaScript,  Angular expressions are code snippets which can be commonly located in binding together with

The key difference between the JavaScript expressions and Angular expressions

Context :In Angular, the expressions are evaluated against a scope item, at the same time as the Javascript expressions are evaluated towards the global window

Forgiving:In Angular expression evaluation is forgiving to null and undefined, at the same time as in Javascript undefined houses generates TypeError or ReferenceError

No Control Flow Statements:Loops, conditionals or exceptions can not be used in an angular expression

Filters:To format information earlier than displaying it you can use filters

Q6. With options on web page load how you may initialize a pick field ?

Ans: You can initialize a pick container with options on page load through the usage of ng-init directive

<div ng-controller = “ apps/dashboard/account ” ng-switch

On = “! ! Accounts” ng-init = “ loadData ( ) ”>

Q7. Explain what are directives ? Mention a number of the maximum generally used directives in AngularJS software ? 

Ans: A directive is some thing that introduces new syntax, they're like markers on DOM element which attaches a unique behavior to it. In any AngularJS software, directives are the most essential components.

Some of the normally used directives are ng-model, ng-App, ng-bind, ng-repeat , ng-show and so forth.

Q8. Mention what are the benefits of the use of AngularJS ?

Ans: AngularJS has several advantages in net improvement.

AngularJS supports MVC sample

Can do two ways information binding using AngularJS

It has in line with-described shape validations

It helps each customer server conversation

It helps animations

Q9. Explain what Angular JS routes does ?

Ans: Angular js routes allow you to create exclusive URLs for distinctive content material for your utility.  Different URLs for distinct content material permits consumer to bookmark URLs to precise content material.  Each such bookmarkable URL in AngularJS is called a route

A fee in Angular JS is a simple object.  It may be a variety of, string or JavaScript object.  Values are generally used as configuration injected into factories, services or controllers. A price must be belong to an AngularJS module.

Injecting a fee into an AngularJS controller feature is done by means of including a parameter with the equal call as the price

Q10. Explain what is statistics binding in AngularJS ?

Ans: Automatic synchronization of facts between the model and consider components is referred as facts binding in AngularJS.  There are 3 approaches for records binding

Data mining in classical template structures

Data binding in angular templates

 What makes AngularJS better ?

Registering Callbacks:There is not any want to register callbacks . This makes your code easy and clean to debug.

Control HTML DOM programmatically:  All the software which can be created the use of Angular never should manage the DOM despite the fact that it may be finished if it's miles required

Transfer information to and from the UI: AngularJS facilitates to remove nearly all of the boiler plate like validating the shape, showing validation mistakes, returning to an internal version and so forth which occurs due to go with the flow of marshalling statistics

No initilization code: With AngularJS you may bootstrap your app without problems the usage of offerings, which automobile-injected into your software in Guice like dependency injection style.

Q11.What is dependency injection and the way does it paintings?

Ans: AngularJS became designed to spotlight the power of dependency injection, a software program design pattern that locations an emphasis on giving components their dependencies instead of hard coding them within the factor. For example, if you had a controller that needed to access a list of clients, you'll shop the actual list of clients in a provider that can be injected into the controller instead of hardcoding the list of clients into the code of the controller itself. In AngularJS you could inject values, factories, offerings, providers, and constants

Q12.Explain what is string interpolation in Angular.Js ?

Ans: In Angular.Js the compiler in the course of the compilation procedure suits textual content and attributes using interpolate carrier to look if they consists of embedded expressions.  As a part of everyday digest cycle these expressions are updated and registered as watches.

Q13. Mention the steps for the compilation method of HTML occurs?

Ans: Compilation of HTML procedure happens in following approaches

Using the standard browser API, first the HTML is parsed into DOM

By using the decision to the $compile () method, compilation of the DOM is completed.  The approach traverses the DOM and matches the directives.

Link the template with scope through calling the linking characteristic again from the preceding step

Q14. Explain what's directive and Mention what are the one of a kind forms of Directive?

Ans: During compilation process while unique HTML constructs are encountered a behaviour or function is precipitated, this characteristic is referred as directive.  It is done whilst the compiler encounters it within the DOM.

Different forms of directives are

Element directives

Attribute directives

CSS elegance directives

Comment directives

Q15. Explain what's linking characteristic and form of linking function?

Ans: Link combines the directives with a scope and produce a stay view.  For registering DOM listeners as well as updating the DOM, hyperlink feature is responsible. After the template is cloned it's far performed.

Pre-linking function: Pre-linking feature is completed before the kid elements are related.  It is not taken into consideration as the safe way for DOM transformation.

Post linking characteristic: Post linking function is performed after the kid elements are linked. It is safe to do DOM transformation by using publish-linking characteristic

HubSpot Video
 

Q16.Explain what's injector?

Ans: An injector is a carrier locator.  It is used to retrieve item times as defined by way of provider, instantiate types, invoke techniques and cargo modules.  There is a single injector consistent with Angular software, it helps to appearance up an item instance by using its name.

Q17. Explain what's the distinction among hyperlink and bring together in Angular.Js?

Ans:

Compile characteristic: It is used for template DOM Manipulation and accumulate all of the directives.

Link feature: It is used for registering DOM listeners in addition to example DOM manipulation. It is performed as soon as the template has been cloned.

Q18. Explain what's manufacturing unit technique in AngularJS?

Ans: For developing the directive, factory technique is used.  It is invoked most effective once, whilst compiler suits the directive for the primary time.  By the use of $injector.Invoke the factory technique is invoked.

Q19. Mention what are the styling shape that ngModel adds to CSS training ?

Ans: ngModel provides those CSS training to allow styling of shape in addition to control

ng- valid

ng- invalid

ng-pristine

ng-grimy

Q20. Mention what are the characteristics of “Scope”?

Ans:

To observer version mutations scopes offer APIs ($watch)

To propagate any version adjustments via the gadget into the view from outdoor of the Angular realm

A scope inherits homes from its discern scope,  while offering access to shared model residences, scopes may be nested to isolate software components

Scope offers context towards which expressions are evaluated

Q21. Explain what is DI (Dependency Injection ) and how an object or characteristic can get a keep of its dependencies ?

Ans: DI or Dependency Injection is a software layout pattern that deals with how code receives maintain of its dependencies.  In order to retrieve factors of the application that is required to be configured whilst module gets loaded , the operation “config” uses dependency injection.

These are the methods that object makes use of to maintain of its dependencies

Typically the use of the new operator, dependency may be created

By regarding a worldwide variable, dependency can be looked up

Dependency may be handed into where it is required

Q22. Mention what are the blessings of the use of Angular.Js framework ?

Ans: Advantages of the use of Angular.Js as framework are

Supports two manner records-binding

Supports MVC sample

Support static template and angular template

Can upload custom directive

Supports REST complete offerings

Supports form validations

Support each patron and server verbal exchange

Support dependency injection

Applying Animations

Event Handlers

Q23. Explain the idea of scope hierarchy?  How many scope can an software have?

Ans: Each angular application consist of one root scope but can also have numerous infant scopes. As baby controllers and a few directives create new toddler scopes, software can have more than one scopes. When new scopes are formed or created they may be brought as a youngsters in their figure scope. Similar to DOM, in addition they creates a hierarchical shape.

Q24.Explain what is the difference among AngularJS and resolution.Js?

Ans: AngularJS combines the functionalities of maximum of the third celebration libraries, it supports man or woman functionalities required to develop HTML5 Apps.  While Backbone.Js do their jobs in my view.

Q25. What Is Data Binding? How Many Types Of Data Binding Directives Are Provided By AngularJS?

Ans: Data binding is the relationship bridge among view and commercial enterprise good judgment (view model) of the software. Data binding in AngularJs is the automated synchronization between the version and view. When the version modifications, the view is robotically up to date and vice versa. AngularJs support one-way binding as well as -manner binding.

AngularJS provides the following information binding directives:

1) <ng-bind>- It updates the textual content content of the desired HTML element with the cost of the given expression. This textual content content material gets up to date when there may be any exchange within the expression. It may be very much like double curly markup ( ) but much less verbose.

It has the following Syntax.

     <ANY ELEMENT ng-bind="expression"> </ANY ELEMENT>
 

2) <ng-bind-html>- It evaluates the expression and inserts the HTML content material into the detail in a cozy way. To use this functionality, it has to apply $sanitize service. For this, it's miles mandatory that $sanitize is to be had.

It has the subsequent Syntax.

     <ANY ELEMENT ng-bind-html=" expression "> </ANY ELEMENT>
 

3) <ng-bind-template>- It replaces the detail text content with the interpolation of the template. It can contain a couple of double curly markups.

It has the following Syntax.

     <ANY ELEMENT ng-bind-template=" … "> </ANY ELEMENT>
 

4) <ng-non-bindable>- This directive informs AngularJS, not to bring together or bind the contents of the cutting-edge DOM detail. It is beneficial in the case whilst the user wants to display the expression only and do no longer want to execute it.

It has the subsequent Syntax.

     <ANY ELEMENT ng-non-bindable > </ANY ELEMENT>
 

five) <ng-model>- This directive may be bound with enter, select, text area or any custom shape manipulate. It gives -way records binding. It additionally offers validation conduct. It additionally retains the kingdom of the manage (like legitimate/invalid, touched/untouched and so forth).

It has the following Syntax.

     <input ng-bind="expression"/>
 

Q26. What Directives Are Used To Show And Hide HTML Elements In AngularJS?

Ans: The directives used to show and conceal HTML factors within the AngularJS are <ng-show> and <ng-hide>. They do that primarily based on the end result of an expression.

Its syntax is as follows.

     <element ng-show="expression"></element>

When the expression for <ng-show> evaluates to proper, then HTML detail(s) are proven at the page, in any other case the HTML detail is hidden. Similarly, <ng-hide> directive hides the HTML detail if the expression evaluates to actual.

Let’s take the subsequent example.

 
 

 

 

<div ng-controller="MyCtrl">

<div ng-show="data.IsShow">ng-display Visible</div>

<div  ng-hide="data.IsHide">ng-cover Invisible</div>

</div>

<script>

var  app = angular.Module("app", []);

app.Controller("MyCtrl", characteristic ($scope) 

$scope.Statistics = ;

$scope.Facts.IsShow = true;

$scope.Statistics.IsHide =  real;

);

</script>

 

Q27. Explain The Directives Ng-If, Ng-Switch, And Ng-Repeat?

Ans:  <Ng-If>.

This directive can upload/remove HTML elements from the DOM primarily based on an expression. If the expression is authentic, it adds a replica of HTML factors to the DOM. If the expression evaluates to fake, this directive gets rid of the HTML element 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", characteristic ($scope) 

$scope.Facts = ;

$scope.Statistics.IsVisible = true;

);

</script>

 

B) <Ng-Switch>.

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

Child factors with the <ng-switch-when> directive may be displayed if it gets a match, else the element and its youngsters get eliminated. It also permits defining a default section, through the use of the <ng-switch-default> directive. It displays a segment if none of the other sections fit.

Let’s see the following instance that shows the syntax for <ng-switch>.

     <div ng-controller="MyCtrl">

<div ng-switch on="data.Case">

<div ng-switch-when="1">Shown whilst case is 1</div>

<div ng-switch-when="2">Shown when case is two</div>

<div ng-switch-default>Shown when case is some thing else than 1 and 2</div>

</div>

</div>

<script>

var app = angular.Module("app", []);

app.Controller("MyCtrl", function ($scope) 

$scope.Facts = ;

$scope.Records.Case = genuine;

);

</script>

 

C) <Ng-Repeat>.

This directive is used to iterate over a collection of objects and generate HTML from it.

 

     <div ng-controller="MyCtrl">

<ul>

<li ng-repeat="name in names">

AngularJS Interview Questions and Answers

</li>

</ul>

</div>

<script>

var app = angular.Module("app", []);

app.Controller("MyCtrl", characteristic ($scope) 

$scope.Names = [ 'Mahesh', 'Raj', 'Diksha' ];

);

</script>

 

Q28. Explain The Set Of “Special” Variables Supported With <Ng-Repeat> Directive?

Ans:  The <ng-repeat> directive has a set of special variables which can be useful at the same time as iterating the collection.

These variables are as follows.

$index

$first

$center

$ultimate

The “$index” carries the index of the element being iterated. The variables $first, $center and $last returns a boolean fee relying on whether the current item is the primary, middle or closing element in the collection being iterated.

     <html>

<script src="http://ajax.Googleapis.Com/ajax/libs/angularjs/1.4.8/angular.Min.Js"></script>

<head>

<script>

var app = angular.Module("app", []);

app.Controller("ctrl", function ($scope)

$scope.Employees = [

name: 'A',

gender: 'alphabet'

,

name: 'B',

gender: 'number'

,

name: 'C',

gender: 'alphanumeric'

,

name: 'D',

gender: 'special character'

];

);

</script>

</head>

<body ng-app="app">

<div ng-controller="ctrl">

<ul>

<li ng-repeat="employee in employees">

<div> is a . <span ng-if="$first">

<strong>(first detail observed)</strong>

</span> <span ng-if="$middle">

<strong>(middle detail located)</strong>

</span> <span ng-if="$last">

<strong>(last element observed)</strong>

</span>

</div>

</li>

</ul>

</div>

</body>

</html>

The output is as follows.

1

2

3

four

A is a alphabet. (first element determined)

B is a variety of. (middle element determined)

C is a alphanumeric. (middle element discovered)

D is a unique character. (closing detail discovered)

 

29. What Is A Factory Method In AngularJS?

Ans: A manufacturing unit is a easy function which permits you to add some logic before creating the item. In the stop, it returns the created object.

Syntax.

1    app.Manufacturing unit('serviceName',function() go back serviceObj;)

Creating Service Using The Factory Method.

      <script>

//developing module

var app = angular.Module('app', []);

//define a factory the use of manufacturing unit() feature

app.Manufacturing unit('MyFactory', function () 

var serviceObj = ;

serviceObj.Function1 = function () 

//TO DO:

;

serviceObj.Function2 = characteristic () 

//TO DO:

;

return serviceObj;

);

</script>

 

Q30. Explain What Is String Interpolation In AngularJS?

Ans: During the compilation system, AngularJS compiler fits textual content and attributes the use of interpolate carrier to peer if it carries embedded expressions.

During normal, digest life cycle, those expressions are up to date and registered as watches.

Q31. Explain AngularJS Application Life-Cycle?

Ans: Understanding the lifestyles cycle of an AngularJS utility makes it simpler to study the way to layout and put into effect the code. Apps lifestyles cycle includes following three levels- bootstrap, compilation, and runtime.

These 3 levels of the lifestyles cycle arise on every occasion a web web page of an AngularJS software gets loaded within the browser. Let’s study each of the three phases in element:

The Bootstrap Phase –In this section, the browser downloads the AngularJS javascript library. After this, AngularJS initializes its essential components and the modules to which the ng-app directive points. Now that the module has loaded, required dependencies are injected into it and turn out to be to be had to the code inside that module.

The Compilation Phase –The second section of the AngularJS lifestyles cycle is the HTML compilation degree. Initially, while a web web page hundreds within the browser, a static shape of the DOM gets loaded. During the compilation phase, this static DOM gets replaced with a dynamic DOM which represents the app view. There are two principal steps – first, is traversing the static DOM and accumulating all the directives. These directives are actually connected to an appropriate JavaScript capability which lies either within the AngularJS built-in library or custom directive code. The mixture of directives and the scope, produce the dynamic or stay view.

The Runtime Data Binding Phase –This is the very last section of the AngularJS application. It survives till the user reloads or navigates faraway from the website. At this point, any changes in the scope get reflected in the view, and any modifications inside the view are at once up to date within the scope, making the scope the unmarried source of information for the view.

This indicates that AngularJS behaves differently from traditional strategies of binding information. The conventional strategies combine a template with facts, acquired from the engine after which manipulate the DOM every time there is any trade in the data.

However, AngularJS compiles the DOM simplest as soon as after which links the compiled template as necessary, making it an awful lot greater efficient than the conventional methods.

Q32. Explain AngularJS Scope Life-Cycle?

Ans: After the angular app receives loaded into the browser, scope statistics passes thru one-of-a-kind tiers called as its existence cycle. Learning approximately this cycle allows us to understand the interaction among scope and other AngularJS components.

The scope facts traverses via the following levels.

Creation –This phase initializes the scope. During the bootstrap process, the $injector creates the foundation scope for the application. And at some stage in template linking, some directives create new child scopes. A digest loop additionally receives created in this section that interacts with the browser event loop. This loop is accountable for updating DOM elements with the adjustments made to the model as well as executing any registered watcher functions.

Watcher registration –This section registers watchers for scope created in the above point. These watches propagate the model adjustments to the DOM factors, mechanically. We can also check in our own watcher’s on a scope via the use of the $watch() function.

Model mutation –This section takes place whilst there's any trade in the scope information. When we do any change in the angular app code, the scope feature <$apply()> updates the version and then calls the <$digest()> function to replace the DOM factors and the registered watches. However, while we exchange the scope inside the angular code like within controllers or services, angular internally calls <$apply()> function for us. But, when we do the adjustments to the scope outside the angular code, we've got to name the <$apply()> characteristic explicitly at the scope, to force the version and DOM to be updated efficiently.

Mutation commentary –This segment takes place, when the digest loop execute the $digest() function at the stop of $practice() name. When the $digest() characteristic executes, it evaluates all watches for version modifications. If there is a exchange in the value, $digest() calls the $watch listener and updates the DOM elements.

Scope destruction –This phase happens whilst the kid scopes which can be now not wished, are removed from the browser’s memory by using the $destroy() feature. It is the duty of the child scope creator to damage them via scope.$ruin() API. This stops propagation of $digest calls into the kid scopes and allows the browsers’ rubbish collector to reclaim the unused memory.

Q33. What Is An Auto Bootstrap Process In AngularJS?

Ans: AngularJS initializes mechanically upon the “DOMContentLoaded” event or whilst the browser downloads the angular.Js script and on the same time file.ReadyState is about to ‘entire’. At this factor, AngularJS appears for the ng-app directive which is the foundation of Angular app compilation manner.

If the ng-app directive is located, then AngularJS will do the subsequent.

Load the module related to the directive.

Create the application injector.

Compile the DOM beginning from the ng-app root element.

This system is vehicle-bootstrapping.

Following is the pattern code that facilitates to apprehend it extra honestly:

     <html>

<body ng-app="myApp">

<div ng-controller="Ctrl">Hello !</div>

<script src="https://ajax.Googleapis.Com/ajax/libs/angularjs/1.4.5/angular.Min.Js"></script>

<script>

var app = angular.Module('myApp', []);

app.Controller('Ctrl', characteristic($scope) 

$scope.Msg = 'Welcome';

);

</script>

</body>

</html>

 

Q34. What Is The Manual Bootstrap Process In AngularJS?

Ans: Sometimes we may additionally want to manually initialize Angular app so that you can have greater control over the initialization procedure. We can do this by the use of angular.Bootstrap() feature inside angular.Element(report).Prepared() function. AngularJS fires this function when the DOM is prepared for manipulation.

The angular.Bootstrap() function takes two parameters, the report, and module call injector.

Following is the pattern code that facilitates to understand the idea greater virtually.

     <html>

<body>

<div ng-controller="Ctrl">Hello !</div>

<script src="https://ajax.Googleapis.Com/ajax/libs/angularjs/1.4.5/angular.Min.Js"></script>

<script>

var app = angular.Module('myApp', []);

app.Controller('Ctrl', feature($scope) 

$scope.Msg = 'Welcome';

);

//guide bootstrap technique

angular.Detail(report).Prepared(feature ()  angular.Bootstrap(report, ['myApp']); );

</script>

</body>

</html>

 

Q35. How To Bootstrap Your Angular App For Multiple Modules?

Ans: Bootstrap for a couple of modules may be carried out by means of the use of following  strategies.

 Automatic bootstrap –AngularJS is routinely initialized for one module. When we have more than one modules, we integrate them right into a single module and thus the angular app could be mechanically initialized for the newly created module. Other modules act as dependent modules for this newly created module.

Let’s take an instance, assume we have  modules: module1 and model2. To initialize the app mechanically, primarily based on those  modules following code is used:

     <html>

<head>

<title>Multiple modules bootstrap</title>

<script src="lib/angular.Js"></script>

<script>

//module1

var app1 = angular.Module("module1", []);

app1.Controller("Controller1", function ($scope) 

$scope.Name = "Welcome";

);

 

//module2

var app2 = angular.Module("module2", []);

app2.Controller("Controller2", feature ($scope) 

$scope.Name = "World";

);

 

//module3 depending on module1 & module2

angular.Module("app", ["module1", "module2"]);

</script>

</head>

<body>

<!--angularjs autobootstap process-->

<div ng-app="app">

<h1>Multiple modules bootstrap</h1>

<div ng-controller="Controller2">

</div>

<div ng-controller="Controller1">

</div>

</div>

</body>

</html>

 

 Manual bootstrap –We can manually bootstrap the app by way of using angular.Bootstrap() feature, for multiple modules.

The above instance may be rewritten for a guide bootstrap system as given underneath.

     <html>

<head>

<title>Multiple modules bootstrap</title>

<script src="lib/angular.Js"></script>

<script>

//module1

var app1 = angular.Module("module1", []);

app1.Controller("Controller1", function ($scope) 

$scope.Call = "Welcome";

);

 

//module2

var app2 = angular.Module("module2", []);

app2.Controller("Controller2", feature ($scope) 

$scope.Call = "World";

);

 

//guide bootstrap manner

angular.Element(report).Ready(function () 

var div1 = record.GetElementById('div1');

var div2 = file.GetElementById('div2');

 

//bootstrap div1 for module1 and module2

angular.Bootstrap(div1, ['module1', 'module2']);

 

//bootstrap div2 most effective for module1

angular.Bootstrap(div2, ['module1']);

);

 

Q36. What Are Compile, Pre, And Post Linking In AngularJS?

Ans:

A) Compile –It collects an HTML string or DOM right into a template and produces a template function. It can then be used to hyperlink the scope and the template together.

AngularJS uses the compile feature to trade the original DOM earlier than creating its example and earlier than the introduction of scope.

Before discussing the Pre-Link and the Post-Link features let’s see the Link function in detail.

B) Link –It has the responsibility of linking the version to the available templates. AngularJS does the facts binding to the compiled templates using Link.

Following is the Link syntax.

     Hyperlink: characteristic LinkFn(scope, detail, attr, ctrl)

where every of the 4 parameters is as follows.

Scope –It is the scope of the directive.

Detail –It is the DOM detail wherein the directive needs to be implemented.

Attr-It is the Collection of attributes of the DOM detail.

Ctrl – It is the array of controllers required by using the directive.

AngularJS lets in setting the link property to an item additionally. The gain of getting an item is that we are able to break up the link characteristic into  separate strategies known as, pre-link and post-link.

C) Post-Link –Execution of Post-Link characteristic begins after the linking of child elements. It is safer to do DOM transformation during its execution. The submit-link characteristic is appropriate to execute the common sense.

D) Pre-Link –It receives finished earlier than the kid elements are linked. It isn't always safe to do DOM transformation. As the compiler linking function will fail to discover the perfect factors.

It is right to use the pre-hyperlink feature to enforce the good judgment that runs when AngularJS has already compiled the child elements. Also, earlier than any of the child detail’s submit-hyperlink functions have been known as.

Let’s see an example that talks approximately Compile, Pre-Link, and Post-Link capabilities.

     <html>

<head>

<title>Compile vs Link</title>

<script src="lib/angular.Js"></script>

<script type="text/javascript">

var app = angular.Module('app', []);

feature createDirective(call)

return feature()

return 

restriction: 'E',

compile: characteristic(tElem, tAttrs)

console.Log(name + ': assemble');

go back 

pre: function(scope, iElem, iAttrs)

console.Log(name + ': pre hyperlink');

,

put up: characteristic(scope, iElem, iAttrs)

console.Log(name + ': post hyperlink');

 

app.Directive('levelOne', createDirective('levelOne'));

app.Directive('levelTwo', createDirective('levelTwo'));

app.Directive('levelThree', createDirective('levelThree'));

</script>

</head>

<body ng-app="app">

<level-one>

<level-two>

<level-three>

Hello AngularJS Interview Questions and Answers

</level-three>

</level-two>

</level-one>

</body>

</html>

     Output:

Hello

           
 

Q37. What Is A Controller In AngularJS?

Ans: A Controller is a fixed of JavaScript capabilities that's certain to a distinct scope, the ng-controller directive. Angular creates a brand new instance of the Controller item to inject the brand new scope as a dependency. The role of the Controller is to reveal facts to our view thru $scope and upload capabilities to it, which includes commercial enterprise good judgment to decorate view behavior.

Controller Rules.

A Controller helps in putting in the initial state of the scope item and outline its behavior.

The Controller need to not be used to manipulate the DOM because it incorporates best commercial enterprise logic. Rather, for manipulating the DOM, we should use facts binding and directives.

Do no longer use Controllers to format input. Rather, using angular shape controls is suggested for that.

Controllers must not be used to percentage code or states. Instead, use angular services for it.

Steps For Creating A Controller.

It needs ng-controller directive.

Next step is to add Controller code to a module.

Name your Controller based totally on capability. Its call should observe camel case format (i.E. SampleController).

Set up the initial nation of the scope item.

Declaring a Controller the usage of ng-Controller directive.

     <div ng-app="mainApp" ng-controller="SampleController">

</div>

Following code presentations the definition of SampleController.

     <script>

feature SampleController($scope) 

$scope.Sample = 

firstSample: "INITIAL",

lastSample: "Initial",

 

fullName: function() 

var sampleObject;

sampleObject = $scope.Pattern;

go back sampleObject.FirstSample + " " + sampleObject.LastSample;

;

</script>

 

38. What Does A Service Mean In AngularJS? Explain Its Built-In Services?

Ans: Services are features that are bound to carry out unique tasks in an utility.

It offers us a method, that facilitates in preserving the angular app statistics for its lifetime.

It offers us strategies, that facilitate to switch information across the controllers in a regular manner.

It is a singleton item and its example is created only as soon as in keeping with application.

It is used to arrange and proportion, statistics and feature throughout the application.

Two most important execution characteristics of angular services are that they may be Singleton and lazy instantiated.

 Lazily instantiated –

It way that AngularJS instantiates a carrier best when a component of an application needs it. This is accomplished by way of the use of dependency injection technique, that makes the Angular codes, robust and less errors inclined.

 Singletons –

Each software element depending on the service, paintings with the unmarried instance of the carrier created via the AngularJS.

Let us take an instance of a completely simple provider that calculates the rectangular of a given wide variety:

     var CalculationService = angular.Module('CalculationService', [])

.Provider('Calculation', function () 

this.Rectangular = characteristic (a)  go back a*a;

);

AngularJS Internal Services –

AngularJS affords many integrated services. Each of them is chargeable for a selected task. Built-in offerings are constantly prefixed with the $ symbol.

Some of the typically used services in any AngularJS software are as follows:

$http –used to make an Ajax name to get the server data.

$window –Provides a reference to a DOM item.

$Location –Provides reference to the browser area.

$timeout –Provides a reference to window.Set timeout function.

$Log –used for logging.

$sanitize –Used to keep away from script injections and show uncooked HTML within the web page.

$Rootscope –Used for scope hierarchy manipulation.

$Route –Used to show browser based totally path in browser URL.

$Filter –Used for presenting filter out get entry to.

$useful resource –Used to work with Restful API.

$file –Used to get admission to the window. Document object.

$exceptionHandler –Used for dealing with exceptions.

$q –Provides a promise object.

$cookies –This provider is useful to jot down, study and delete browser cookies.

$parse –This service is useful to transform AngularJS expression right into a characteristic.

$cacheFactory –This carrier evaluates the desired expression while the person modifications the input.

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

Ans: There are 5 one-of-a-kind methods to create offerings in AngularJS.

Value

Factory

Service

Provider

Constant

Let’s talk, each of the above AngularJS service types one at a time with code instance:

1. AngularJS Value.

It is the best service kind supported by means of AngularJS that we will create and use. It is similar to a key-value pair or like a variable having a price. It can shop handiest a single cost. Let’s take an instance and create a carrier that shows username:

     var app=angular.Module("app",[]);

app.Cost("username","Madhav");

Code to apply “Value”:

We can use this carrier everywhere by using the use of dependency injection. Following instance injects the service in a controller:

     app.Controller("MainController",characteristic($scope, username)

$scope.Username=username;

);

In the above example, we've created a Value provider “username” and used it in MainController.

2. AngularJS Factory.

Value service can be very easy to write down however, it lacks many critical functions. So, the subsequent provider type we will have a look at is “Factory” carrier. After its advent, we are able to even inject different offerings into it. Unlike Value service, we can't upload any dependency in it.

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

     App.Manufacturing facility("username",characteristic()

var call="John";

return 

name:name

);

The above code suggests that Factory service takes “function” as an issue. We can inject any wide variety of dependencies or techniques in this “feature” as required with the aid of this carrier. This characteristic must return some object. In our instance, it returns an item with the assets name. Now, allow us to look, as to how we will use this provider:

Code to apply “Factory”:

The characteristic returns an item from provider which has a property name so we can get right of entry to it and use it everywhere. Let’s see how we are able to use it within the controller:

     app.Controller("MainController",function($scope, username)

$scope.Username=username.Name;

);

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

3. AngularJS Service.

It works identical as the “Factory” provider. But, instead of a characteristic, it gets a Javascript class or a constructor function as an issue. Let’s take an example. Suppose we've got a feature:

1

2

three

characteristic MyExample(num)

this.Variable="fee";

Now, we need to transform the characteristic right into a service. Let’s take a look at how we can try this with “Factory” technique:

     app.Factory("MyExampleService",["num" ,function(num)

return new MyExample(num);

]);

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

1    app.Provider("MyExampleService",["num", MyExample]);

Thus, we have known as the provider approach at the module and provided its name, dependency, and the name of the function in an array.

Four. AngularJS Provider.

It is the determine of all of the carrier types supported by using AngularJS, except the “Constant” that we can talk within the subsequent phase. It is the center of all of the provider sorts. Thus we are able to say that other offerings work on pinnacle of it. It allows us to create a configurable service that need to enforce the <$get> technique.

We use this provider to expose the API that is chargeable for doing the software-huge configuration. The configuration must complete before starting the application.

Let’s take an example.

     App.Issuer('authentication', function() 

var username = "John";

return 

set: function(newUserName) 

username = newUserName;

,

$get: feature() 

characteristic getUserName() 

go back username;

go back 

getUserName: getUserName

;

;

);

This instance initializes a provider with its call as “authentication”. It additionally implements a <$get> characteristic, which returns a technique “getUsername” which in flip returns the private variable known as username. This additionally has a setter, the use of it we are able to set the username on application startup as follows:

     app.Config(["authenticationProvider", function(authenticationProvider) 

authenticationProvider.Set("Mihir");

]);

5. AngularJS Constant.

As the name shows, this provider allows us to declare constants in our application. We can then use them wherever needed, just by adding it as a dependency. There are many locations, in which we use constants like a few base URLs, utility name, and so on.

We simply define them once and use them everywhere as in line with our need. Thus, this technique lets in us to jot down the definition at one location. If there is any exchange within the value later, we have to do the changes at one vicinity best.

Here is an example of the way we can create constants:

     app.Regular('applicationName', 'Service Tutorials');
 

Q40. What Is The Difference Between The $Watch, $Digest, And $Apply?

Ans: In AngularJS $scope object is having special features




CFG