Angular Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on Angular

Question 1.
What is Angular JS?
Answer:
“AngularJS is a JavaScript framework which simplifies binding JavaScript objects with HTML Ul elements.”
Let us try to understand the above definition with simple sample code.
Below is a simple “Customer” function with the “CustomerName” property. We have also created an object called “Cust” which is of the “Customer” class type.

function Customer( )
{
    this.CustomerName = "Angularlnterview";
}
var Cust = new Customer( );

Now let us say the above customer object we want to bind to a HTML textbox called as “Txtcus tomerName”. In other words when we change something in the HTML textbox the customer object should get updated and when something is changed internally in the customer object the Ul should get updated.

<input type=text id=’TxtCustomerName” onchange=”UitoObject( )”/>

So in order to achieve this communication between Ul to object developers end up writing functions as shown below. “UitoOb j ect” function takes data from Ul and sets it to the object while the other function “Obj ecttoui” takes data from the object and sets it to Ul.

function UitoObject( )
{
      Cust.CustomerName = $("#TxtCustomerName").val( );
}
function ObjecttoUi( )
{
     $("#TxtCustomerName").val(Cust.CustomerName);
}

So if we analyze the above code visually it looks something as shown in Figure 8.1. Your both functions are nothing but binding code logic which transfers data from Ul to object and vice versa.

Angular Interview Questions in . NET chapter 8 img 1

Now the same above code can be written in Angular as shown below. The JavaScript class is attached to a HTML parent div tag using “ng-controller” directive and the properties are bonded directly to the text box using “ng-model” declarative.

So now whatever you type in the textbox updates the “Customer” object and when the “Customer” object gets updated it also updates the Ul.

<div ng-controller="Customer">
<input type=text id="txtCustomerName" ng-model="CustomerName"/>
</div>

in short if you now analyze the above code visually you end up with something as shown in the below Figure 8.2. You have the VIEW which is in HTML, your MODEL objects which are javascript functions and the binding code in Angular.

Angular Interview Questions in . NET chapter 8 img 2

Now that binding code have different vocabularies.

  • Some developers called it “ViewModel” because it connects the “Model” and the “View”.
  • Some called it “Presenter” because this logic is nothing but presentation logic.
  • Some termed it as “Controller” because it controls how the view and the model will communicate.

To avoid this vocabulary confusion Angular team has termed this code as “WHATEVER”. It’s that “WHATEVER” code which binds the Ul and the Model. That’s why you will hear lot of developers saying Angular implements “MVW” architecture.

Question 2.
Explain directives in Angular.
Answer:
Directives are attributes decorated on the HTML elements. All directives start with the word “ng”. As the name says directive it directs Angular what to do.

For example below is a simple “ng-model” directive which tells angular that the HTML textbox ” txtCus tomerName ” has to be binded with the “CustomerName” property.

<input type=text id=”txtCustomerName” ng-modei=”CustomerName”/>

Some of the most commonly used directives are ng-app, ng-controller and ng-repeat.

Question 3.
What are controllers and need of ng-controller and ng-model in Angular?
Answer:
“Controllers” are simple JavaScript function which provides data and logic to HTML Ul as shown in Figure 8.3. As the name says controller they control how data flows from the server to HTML Ul.

Angular Interview Questions in . NET chapter 8 img 3

For example below is simple “Customer” controller which provides data via “CustomerName” and “CustomerCode” properties and Add/ Update logic to save the data to database.

Note: Do not worry too much about the $ scope, we will discuss the same in the next question.
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 Ul 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 Ul which is attached to the “Customer” controller via the “ng-controller” directive and the properties are bonded using “ng-model” directive.

<div ng-controller="Customer">
<input type=text id="Cust:omerName" ng-model= "CustomerName"/xbr />
<input type=text id="CustomerCode" ng-model="CustomerCode"/>
</div>

Question 4.
What are expressions in Angular?
Answer:
Angular expressions are unit of code which resolves to value. This code is written inside curly braces “{ }”
Below are some examples of angular expressions:
The below expression adds two constant values.

{{1+1}}

The below expression multiplies quantity and cost to get the total value.

The value total cost is {{ quantity * cost}}

The below expression displays a controller scoped variable.

<divng-controller=”CustomerVM”>

The value of Customer code is {{CustomerCode}}

<div ng-controller="CustomerVM">
         The value of Customer code is {{CustomerCode}}
</div>

Question 5.
How can we initialize Angular application data?
Answer:
We can use the “ng-init” directive to achieve the same. You can see in the below example we have used the “ng-init” directive to initialize the “pi” value.

<body ng-app="myApp" ng-init="pi=3.14">
           The value of pi is {{pi}}
</body>

Question 6.
Explain $scope in Angular?
Answer:
“$scope” is an object instance of a controller. “$scope” object instance get’s created when the “ng- controller” directive is encountered.
For example in the below code snippet we have two controllers “Function1” and “Function2”. In both the controllers we have a “ControlierName” variable.

function Function1($scope)
{
     $scope.ControllerName = "Function1";
}
function Function2($scope)
{
    $scope.ControlierName = "Function2";
}

Now to attach the above controllers to HTML Ul we need to use the “ng-controller” directive. For instance, you can see in the below code snippet how the “ng-controller” directive attaches “Function1” with the “div1” tag and “Function2” with the “div2” tag.

<div id="div1" ng-controller="Function1">
       Instance of {{ControlierName}} created
</div>
<div id="div2" ng-controller="Function2">
      Instance of {{ControlierName}} created
</div>

So this is what happens internally. Once the HTML DOM is created Angular parser starts running on the DOM as shown in Figure 8.4 and following are the sequence of events:

  • The parser first finds “ng-controller” directive which is pointing to “Function1”. It creates a new instance of “$scope” object and connects to the “div1 ” LJI.
  • The parser then starts moving ahead and encounters one more “ng-controller” directive which is pointing to “Function2”. It creates a new instance of “$scope” object and connects to the “div2” Ul.

Angular Interview Questions in . NET chapter 8 img 4

Now once the instances are created, below is a graphical representation of the same. So the “Divi” HTML Ul is binded with “Functionl” $scope instance and the “Div2” HTML Ul is binded with “Function2” $scope instance as shown in Figure 8.5. In other words now anything changes in the $scope object the Ul will be updated and any change in the Ul will update the respective $scope object.

Angular Interview Questions in . NET chapter 8 img 5

Question 7.
What is “$rootScope” and how is it related with “$scope”?
Answer:
“$rootScope” is a parent object of all “$scope” angular objects created in a Web page as shown in Figure 8.6.

Angular Interview Questions in . NET chapter 8 img 6

Let us understand how Angular does the same internally. Figure 8.7 shows a simple Angular code which has multiple “Div” tags and every tag is attached to a controller. So let us understand step-by-step how angular will parse this and how the “$rootScope” and “$scope” hierarchy is created.

Angular Interview Questions in . NET chapter 8 img 7

The Browser first loads the above HTML page and creates a DOM (Document Object Model) and Angular runs over the DOM. Below are the steps how Angular creates the root scope and scope objects.

• Step 1: Angular parser first encounters the “ng-app” directive and creates a “$rootScope” object in memory.

• Step 2: Angular parser moves ahead and finds the expression {{Somevalue}}. It creates a variable from the expression and attaches this variable to the “$rootScope” object created in Step 1.

• Step 3: Parser then finds the first “div” tag with “ng-controller” directive which is pointing to “Function1” controller. Looking at the “ng-controller” directive it creates a “$scope” object instance for “Function1” controller. This object is then attached to the “$rootscope” object.

• Step 4: Step 3 is then repeated by the parser every time it finds a “ng-controller” directive tag. Step 5 and Step 6 is the repetition of Step 3.

If you want to test the above fundamentals you can run the below sample Angular code. In the below sample code we have created controllers “Function1” and “Function2”. We have two counter variables one at the root scope level and other at the local controller level.

<script language=javascript>
function Functioni($scope, $rootScope)
{
       $rootScope.Counter = (($rootScope.Counter || 0) + 1);
       $scope.Counter = $rootScope.Counter;
       $scope.ControllerName = "Function1";
}
function Function2 ($scope, $rootscope)
{
      $rootScope.Counter = (($rootScope.Counter || 0) + 1);
      $scope.ControllerName = "Function2";
}
var app = angular.module("myApp", [ ]); // creating a APP
app.controller("Functionl", Functionl); // Registering the VM
app.controller("Function2", Function2);

</script>

Below is the HTML code for the same. You can we have attached “Functionl” and “Function2 ” two times with ”ng-controller” which means four instances will be created.

<body ng-app="myApp" id=1>
Global value is {{Counter}}<br />
<div ng-controller="Function1">
Child Instance of {{ControllerName}} created: {{Counter}]
</div><br />
<div ng-controller="Function2">
Child Instance of {{ControllerName}} created: {{Counter}}
</div><br />
<div ng-controller="Function1">
Child Instance of {{ControllerName}} created: {{Counter}}
</div><br />
<div ng-controller="Function2">
Child Instance of {{ControllerName}} created: {{Counter}}
</div><br />
</body>

Figure 8.8 the output of the code you can see the global variable of root scope has be incremented four times because four instances of $scope have been created inside “$rootscope” object.

Angular Interview Questions in . NET chapter 8 img 8

Question 8.
Do I need jQuery for Angular?
Answer:
No, you do not need jQuery for Angular. It’s independent of jQuery.

Question 9.
How is the data binding in Angular?
Answer:
Its two-way binding. So whenever you make changes in one entity the other entity also gets

Global value is 4
Child Instance of Function1 created 1 Child Instance of Functio1 created 4 Child Instance of Function1 created 3 Child Instance of Function2 created

Question 10.
Explain compile and link phase.
Answer:
Angular framework is a parser. A parser which parses the Angular directives and render’s HTML output. Angular parser works in three steps:
Step 1: HTML browser parses the HTML and creates a DOM (Document Object Model).
Step 2: Angular framework runs over this DOM looks at the Angular directives and manipulates the DOM accordingly.
Step 3: This manipulated is then rendered as HTML in the browser

Angular Interview Questions in . NET chapter 8 img 9

Now the above angular parsing is not so simple as it looks to be. It occurs in two phases “Compile” and “Link” as shown in Figure 8.9. First the Compile phase executes followed by the Link phase as shown in Figure 8.10. Fl9ure 8.10: Compile Phase

Angular Interview Questions in . NET chapter 8 img 10

In compile phase the angular parser starts parsing the DOM and whenever the parser encounters a directive it create a function. These functions are termed as template or compiled functions. In this phase we do not have access to the $ scope data.
In the link phase the data, i.e., ($scope) is attached to the template function and executed to get the final HTML output as shown in Figure 8.11.

Angular Interview Questions in . NET chapter 8 img 11

Question 11.
How do we make HTTP get and post calls in Angular?
Answer:
To make HTTP calls we need to use the ” $HTTP ” service of Angular. In order to use the HTTP services you need to make provide the “$HTTP” as a input in your function parameters as shown in the below code.

function CustomerController($scope, $HTTP)
{
       $scope.Add = function( )
       {
           $HTTP({ method: "GET", url: "HTTP: //localhost: 8438/SomeMethod"
           }).success(function (data, status, headers, config)
           {
                // Here goes code after success
           }
      }
}

“$HTTP” service API (Application Programming Interface) needs at least three things:

  • First, what is the kind of call “POST” or “GET”.
  • Second is the resource URL on which the action should happen.
  • Third we need to define the “success” function which will be executed once we get the response from the server.
$HTTP({ method: "GET", url: "HTTP: //localhost: 8438/SomeMethod"
}).success(function (data, status, headers, config)
{
     // Here goes code after success
}

Question 12.
How do we pass data using HTTP POST in Angular?
Answer:
You need to pass data using the “data” keyword in the “$HTTP” service API function. In the below code you can see we have created a JavaScript object “myData” with “CustomerName” property. This object is passed in the “$HTTP” function using HTTP POST method.

Var myData = { };
myData.CustomerName = "Test";
$HTTP({ method: "POST",
     data: myData,
     url: "HTTP: //www.xyz.com"})
     .success(function (data, status, headers, config)
     {
        // Here goes'code after success
}

Question 13.
What is dependency injection and how does it work in Angular?
Answer:
Dependency Injection (Dl) is a process where we inject the dependent objects rather than consumer creating the objects. Dl is everywhere in Angular or we can go one step ahead and say Angular cannot work without Dl.
For example, in the below code “$scope” and “$HTTP” objects are created and injected by the angular framework. The consumer, i.e., “CustomerController” does not create these objects himself/herself rather Angular injects these objects.

function customercontroller ($scope, $HTTP)
{
     // your consumer would be using the scope and HTTP objects
}

Question 14.
How does Dl get benefits in Angular?
Answer:
There are two big benefits of Dl: Decoupling and Testing.
Let’s first start with Decoupling. Consider your application has a logger functionality that helps to log errors, warnings, etc., in some central place. This central place can be a file, event viewer, database, etc.

function FileLogger( )
{
this.Log = function ( ) {
alert("File logger");
} ;
}
function EventLogger( )
{
this.Log = function ( ) {
alert("Event viewer logger");
} ;
}

Now let’s say you have a “Customer” class that wants to use the “Logger” classes as shown in Figure 8.12. Now which “Logger” class to be used depends on configuration.

Angular Interview Questions in . NET chapter 8 img 12

So the code of “Customer” is something as shown below. So depending on the configuration “Customer” class either creates “FileLogger” or it creates the “EventLogger” object.

function Customer($scope, Logger)
{
      $scope.Logger = { };
      if (config.Loggertype = "File")
      {
           $scope.Logger = new FileLogger( );
      }
      else
      {
          $scope.Logger = new EventLogger( );
      }
}

But with Dl our code becomes something as shown below. The “Customer” class says it is not worried from where the “Logger” object comes and which type of “Logger” objects are needed. This classes just uses the “Logger” object.

function customer ($scope, $HTTP, Logger)\
{
     $ scope.Logger = Logger;
}

With this approach when a new “Logger” object gets added the “Customer” class does not have to worry about the new changes because the dependent objects are injected by some other system.

The second benefit of Dl is testing. Let’s say you want to test the “Customer” class and you do not have an Internet connection. So your “$HTTP” object method calls can throw errors. But now you can mock a fake * $HTTP” object and run your Customer class offline without errors. The fake object is injected using Dl.

Question 15.
What are services in Angular?
Answer:
Service helps to implement dependency injection. For instance, let’s say we have the below “Customer” Class that needs the “Logger” object. Now “Logger” object can be Of “FileLogger” type or”EventLogger ‘ type-

function Customer($scope, $HTTP, Logger)
{
        $scope.Logger = Logger;
}

So you can use the “service” method of the application and tie up the “EventLogger” object with the “Logger” input parameter of the “Customer” class.

var app = angular.module("myApp", [ ]); // creating a APP
app.controller("Customer", Customer); // Registering the VM
app.service("Logger", EventLogger); // Injects a global Event logger object

So when the controller object is created the “EventLogger” object is injected automatically in the controller class.

Question 16.
Are Service object instances global or local?
Answer:
Angular Services create and inject global instances. For example below is a simple “Hitcounter” class which has a “Hit” function and this function increments the variable count internally every time you call hit the button.

function HitCounter( )
{
      var i = 0;
      this.Hit = function ( )
      {
           i + +;
           alert(i);
      };
}

This “Hitcounter” class object is injected in the “Myciass” class as shown in the below code.

function MyClass($scope, Hitcounter)
{
$scope.HitCounter = HitCounter;
}

The below code advises the Angular framework to inject the “Hitcounter” class instance in the “Myciass” class. Read the last line of the below code especially which says to inject the “Hitcounter” instance.

var app = angular.module("myApp", [ ]); // creating a APP
app.controller("MyClass", MyClass); // Registering the VM
app.service("Hitcounter", Hitcounter); // Injects the object

Now let’s say that the “Controller” “MyClass” is attached to two div tags as shown in Figure 8.13.
So two instances of “MyClass” will be created. When the first instance of “MyClass” is created a “Hitcounter” object instance is created and injected into the “MyClass” first instance.
When the second instance of “MyClass” is created the same “Hitcounter” object instance is injected into the second instance of “MyClass”.
Again I repeat the same instance is injected into the second instance, new instances are not created.

Angular Interview Questions in . NET chapter 8 img 13

If you execute the above code you will see counter values getting incremented even if you are coming through different controller instances.

Question 17.
What is a Factory in Angular?
Answer:
“Factory” in real-world means a premise where products are manufactured. Let’s take an example of a computer manufacturing firm. Now the company produces different kinds and sizes of computers like laptops, desktops, tablets, etc.

Now the process of manufacturing the computer products is are same with slight variation. To manufacture any computer we need a processor, RAM (Random Access Memory), and hard disk. But depending on what kind of final case packing is the final product shapes.

Angular Interview Questions in . NET chapter 8 img 14

Angular as shown in Figure 8.14.
For example see the below code we have a “Customer”, “Phone” and “Address” class.

function Customer( )
{
      this.CustomerCode = "1001";
      this.CustomerName = "Shiv";
}
function Phone( )
{
     this.PhoneNumber = " ";
}
function Address ( )
{
     this.Address1 = " ";
     this.Address2 =" ";
}

 

So now we would create different types of “Customer” object types using the combination of
“Address” and “Phones” object.

  • We would like to combine “Customer” with “Address” and create a “Customer” object which has the “Address” collection inside it.
  • Or must be we would like to create a “Customer” object with “Phone” objects inside it.
  • Or must be a “Customer” object with both “Phone” and “Address” objects.

Angular Interview Questions in . NET chapter 8 img 15

In other words, we would like to have different permutations and combinations to create different types of “Customer” objects.
So let’s start from the bottom. Let’s create two factory functions one which creates the “Address” object and the other which creates “Phone” objects.

function CreateAddress( )
{
      var add = new Address( );
      return add;
}
function CreatePhone( )
{
      var phone = new Phone( );
      return phone;
}

Now let’s create a main factory function that uses the above two small factory functions and gives us all the necessary permutations and combinations.
In the below factory you can see we have three functions:

  • “CreateWithAddress” creates “Customer” with “Address” objects inside it.
  • “CreateWithPhone” creates a “Customer” object with “Phone” objects inside it.
  • “CreateWithPhoneAddress” creates “Customer” Object with aggregated “Phone” and “Address” objects.
function CreateCustomer( )
{
      return
      {
           CreateWithAddress: function ( )
           {
               var cust = new Customer();
               cust.Address = CreateAddress( );
               return cust;
          },
          CreateWithPhone: function ( )
          {
              var cust = new Customer( );
              cust.Phone = { };
              cust.Phone = CreatePhone( );
              return cust;
         }
         CreateWithPhoneAddress: function ( )
         {
             debugger;
             var cust = new Customer( );
             cust.Phone = CreatePhone( );
             cust.Address = CreateAddress( );
             return cust;
        }
     }
}

Below is a simple “CustomerController” which takes “CustomerFactory” as the input. Depending on “TypeOfCustomer” it creates with “Address”, “Phones” or both of them.

function CustomerController($scope, Customerfactory)
{
     $scope.Customer = { };
     $scope.Init = function(TypeofCustomer)
     {
           if (TypeofCustomer == "1")
           {
               $scope.Customer = Customerfactory.CreateWithAddress( );
           }
           if (TypeofCustomer == "2")
           {
               $scope.Customer = Customerfactory.CreateWithPhone( );
           }
           if (TypeofCustomer == "3")
           {
               $scope.Customer =
               Customerfactory.CreateWithPhoneAddress( ) ;
           }
     }
}

You also need to tell Angular that the “CreateCustomer” method needs to be passed in the input. For that, we need to call the “Factory” method and map the “CreateCustomer” method with the input parameter “CustomerFactory” for dependency injection.

var app = angular .module ( "myApp" , [ ]) ; // creating a APP
app.controller("CustomerController", CustomerController); // Register the VM
app.factory("Customerfactory", CreateCustomer);

So if we consume the “CustomerControiier” in Ul, depending on the situation it creates different flavors of the “Customer” object. You can see in Figure 8.16 we have three different “div” tags and depending on the “Typeofcustomer” we are displaying data.

Angular Interview Questions in . NET chapter 8 img 16

Question 18.
What is the difference between Factory and Service?
Answer:
“Factory” and “Service” are different ways of doing Dl (Dependency Injection) in angular. Please read the previous question to understand what is Dl.
So when we define Dl using “service” as shown in the code below. This creates a new global instance of the “Logger” object and injects it into the function.

app. service (“Logger"’, Logger); //Injects a global object

When you define Dl using a ” factory” it does not create an instance. It just passes the method and later the consumer internally has to make calls to the factory for object instances.

app. factory(“Customertactory”, CreateCustomer);

Figure 8.17 depicts visually how Dl process for “Service” is different than “Factory”

Angular Interview Questions in . NET chapter 8 img 17

Factory Service
Usage When we want to create different types of objects

depending on scenarios. For example, depending

on scenario we want to create a simple “Customer”

object, or “Customer” with “Address” object or

“Customer” with “Phone” object. See the previous

question for more detailed understanding.

When we have utility or shared functions to be injected like Utility, Logger, Error handler, etc.
Instance No Instance created. A method pointer is passed. Global and Shared instance is created.

 

Question 19.
How are validations implemented in Angular?
Answer:
Angular leverages HTML 5 validation attributes and new HTML 5 form element types to implement validation as shown in Figure 8.18.

Angular Interview Questions in . NET chapter 8 img 18

For instance below is a simple form which has two textboxes. We have used HTML 5 “required” validation attribute and a form element of type “email”.

<form name="frml" id="frml" >
Name: <input type=text name="CustomerName"
id="CustomerName" required /> Email: <input type=email name="Email" id="Email" />
<input type=submit value="Click here"/>
</form>

Below are some example of new form elements introduced in HTML 5 and Angular works with almost all of them:

  • Color.
  • Date
  • Datetime-local
  • E-mail
  • Time
  • URL
  • Range
  • Telephone
  • Number
  • Search

When you run the above HTML inside a browser which understands HTML 5, you will see your validations and form types in actions as shown in the Figure 8.19.

Angular Interview Questions in . NET chapter 8 img 19

Angular leverages HTML 5 validation attributes and new HTML 5 form elements. Now if we Click here want Angular to handle validation we need HTML 5 to do validation. So for that the first Figure 8.19: Validation and Form Types step is to specify “novalidate” attribute on the form tag.

<form name="frml" novalidate>
</form>

So now the HTML will not fire those validations it will be routed to the Angular engine to further take actions.
In other words when end user fills data in the HTML Ul, validation events are routed to Angular framework and depending on scenario Angular sets a field called as “$valid”. So if the validations are fine it sets it to “True” or else its sets it to “False” as shown in Figure 8.20.

Angular Interview Questions in . NET chapter 8 img 20

So you can see in the below code we have attached the angular controller and models to the text boxes. Watch the code of the button it has “ng-disabied” attribute which is set via the “$vaiid” property in a negated fashion.

Negated fashion means when there is no error it should enable the button and when there are errors that means it is false it should disable the button.

<form name="frml" novalidate>
Name: <input type=text ng-model="Customer.CustomerName" name="CustomerName" required />
Email: <input type=email ng-model="Customer.Email" name="Email" />
<input type=submit value="Click here" ng-disabled="!(frml.$valid)"/>
</form>
Note: “Name” is needed for the validations to work.

Question 20.
How to check error validation for a specific field?
Answer:
To check for a specific field you need to use the below DOM code.

!frm1.CustomerName.$valid

Question 21.
What does SPA (Single Page Application) mean?
Answer:
SPA is a concept where rather loading pages from the server by doing postbacks we create a single shell page or master page and load the Web pages inside that master page.

Question 22.
How can we implement SPA with Angular?
Answer:
By using Angular routes.

Question 23.
How to implement routing in Angular?
Answer:
Implementing Angular route is a five-step process:
Step 1: Add the “angular-route.js” file to your view.

<script src=”~/Scripts/angular-route.js”x/script>

Step 2: Inject “ngRoute” functionality while creating Angular app object.

varapp = angular.module(“myApp”, [‘ngRoute’]);

Step 3: Configure the route provider.
In route provider we need to define which URL pattern will load which view. For instance in the below code we are saying “Home” loads “Yoursite/Home” view and “Search” loads “YourSite/ Search” view.

app.config(['$routeProvider',
    function ($routeProvider) {;
          $routeProvider.
          when('/Home, {
                templateUrl: 'Yoursite/Home',
                controller: 'HomeController'
          }) .
          when('/Search', {
                templateUrl: YourSite/Search',
                controller: 'SearchController'
         }) .
         otherwise({
               redirectTo: '/'
        });
}]);

Step 4: Define hyperlinks.
Define hyperlink with the ” #” structure as shown below. So now when user clicks on the below anchor hyperlinks, these actions are forwarded to route provider and router provider loads the view accordingly.

<div>
<a href="#/Home">Home</axbr /> .
<a href="#/Search"> Search </a><br />
</div>

Step 5: Define sections where to load the view.
Once the action comes to the router provider it needs a place holder to load views. That’s defined by using the “ng-view” tag on a HTML element. You can see in the below code we have created a “Div” tag with a place holder. So the view will load in this section.

<divng-view>
</div>

So if we summarize angular routing is a three-step process. Figure 8.21 shows a visual diagram for the same.

  • Step 1: End user clicks on a hyperlink or button and generates action.
  • Step 2: This action is routed to the route provider.
  • Step 3: The router provider scans the URL (Uniform Resource Locator) and loads the view in the place holder defined by “ng-view” attribute.

Angular Interview Questions in . NET chapter 8 img 21

Question 24.
How can we create a custom directive in Angular?
Answer:
Till now we have looked in to pre-defined Angular directives like “ng-controller”, “ng-model” and so on. But what if we want to create our own custom Angular directive and attach it with HTML elements as shown in the below code.

<divid=footercompany-copy-right></div>

To create a custom directive we need to use the “directive” function to register the directive with angular application. When we call the “register” method of “directive” we need to specify the function which will provide the logic for that directive.
For example, in the below code we have created a copyright directive and it returns a copyright text. Please note “app ” is an Angular application object which has been explained in the previous sections.

app.directive('companyCopyRight', function ( )
{
      return
      {
          template: '@CopyRight questpond.com '
     };
}) ;

The above custom directive can be later used in elements as shown below code.

<div ng-controller="CustomerViewModel">
<div company-Copy-rightx/div>
</div>

Question 25.
What kind of naming conventions is used for custom directives?
Answer:
For angular custom directive the best practice is to follow camel casing and that also with at least two letter’s. In camel case naming convention we start with a small letter, followed by a capital letter for every word.

Some example of camel cases are “loopCounter”, “isValid” and so on. .

So when you register a custom directive it should be with camel case format as shown in the below code “companyCopyRight” and in the Figure 8.22 as well.

app.directive('companyCopyRight', function ( )
{
       return
       {
             template: '@CopyRight questpond.com '
       };
});

Later when this directive is consumed inside HTML before each capital letter of camel case we need to insert a as specified in the below code.

<div company-copy-rightx/div>

If you are making a one letter prefix like “copyright” it is very much possible that tomorrow if HTML team creates a tag with the same name, it will clash with your custom directive. That’s why angular team recommends camel case which inserts a in between to avoid further collision with future HTML tags.

Angular Interview Questions in . NET chapter 8 img 22

Question 26.
What are the different custom directive types in Angular JavaScript?
Answer:
There are different flavors of Angular directives depending till what level you want to restrict your custom directive.
In other words do you want your custom directive to be applied only on HTML element or only on an attribute or just to CSS (Cascading Style Sheet), etc.
So in all there are four different kinds of custom directives:

  • Element directives (E)
  • Attribute directives (A)
  • CSS class directives (C)
  • Comment directives (M)

Below is a simple custom directive implementation at the element level.

myapp.directive('userinfo', function()
{
         var directive = { };
         directive.restrict = 'E';
         directive.template = "User: {{user.firstName}} {{user.lastName}}";
         return directie;
}) ;

The “restrict” property is set to “E” which means that this directive can only be used at element level as shown in the code snippet below.

<userinfox/userinfo>

If you try to use it at an attribute level as shown in the below code it will not work.

<div userinfox/div>

So “E” for element, “A” for attribute, “C” for CSS and “M” for comments.

Question 27.
What if I want custom directives to be applied on element as well as attributes?
Answer:

directive.restrict = ‘EA’;

Question 28.
Can I set an Angular directive template to a HTML Web page?
Answer:
Yes, you can set template to page directly by using “tempiateUri” property of the directive as shown in the code snippet below.

directive.templateUrl = “/templates/footer.html”;

Some more questions of Angular for home work.

What is the need of $.Watch?
What is the difference between $HTTP and $resource?
What are promises in Angular?