Thursday, 22 February 2018

Angular Js Qes & Ans PART-1

1.What is AngularJS ?
“AngularJS is a JavaScript framework which simplifies binding JavaScript objects with HTML UI elements.”
Let us try to understand the above definition with simple sample code.
Below is a simple “Customer” function with “CustomerName” property.
We have also created an object called as “Cust” which is of “Customer” class type.
Hide   Copy Code
function Customer()
{
this.CustomerName = "AngularInterview";
}
var Cust = new Customer();
Now let us say the above customer object we want to bind to a HTML text box called as “TxtCustomerName”.
 In other words when we change something in the HTML text box the customer object should get updated and when something is changed internally in the customer object the UI should get updated.
Hide   Copy Code
<input type=text id="TxtCustomerName" onchange="UitoObject()"/>
So in order to achieve this communication between UI to object developers end up writing functions as shown below. “UitoObject” function takes data from UI and sets it to the object while the other function “ObjecttoUI” takes data from the object and sets it to UI.
Hide   Copy Code
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 below. Your both functions are nothing but binding code logic which transfers data from UI to object and vice versa.
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 binded 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 UI.
Hide   Copy Code
<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.You have the VIEW which is in HTML, your MODEL objects which are javascript functions and the binding code in Angular.
 Now that binding code have different vocabularies.
Some developers called it “ViewModel” because it connects the “Model” and the “View” .
Some call it “Presenter” because this logic is nothing but presentation logic.
Some term it has “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 UI and the Model. That’s why you will hear lot of developers saying Angular implements “MVW” architecture.

2.Explain Directives in Angular?
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 “txtCustomerName” has to be binded with the “CustomerName” property.
Hide   Copy Code
<input type=text id="txtCustomerName"  ng-model="CustomerName"/>
Some of the most commonly used directives are ng-app,ng-controller and ng-repeat.

3. What are controllers and need of ng-controller and ng-model in Angular?
“Controllers” are simple javascript function which provides data and logic to HTML UI. As the name says controller they control how data flows from the server to HTML UI.
For example below is simple “Customer” controller which provides data via “CustomerName” and “CustomerCode” property and Add/ Update logic to save the data to database.
Note: - Do not worry too much about the $scope , we will discuss the same in the next question.
Hide   Copy Code
function Customer($scope)
{
        $scope.CustomerName = "Shiv";
        $scope.CustomerCode = "1001";
        $scope.Add = function () {
        }
        $scope.Update = function () {
        }
}
“ng-controller” is a directive.Controllers are attached to the HTML UI by using the “ng-controller” directive tag and the properties of the controller are attached by using “ng-model” directive. For example below is a simple HTML UI which is attached to the “Customer” controller via the “ng-controller” directive and the properties are binded using “ng-model” directive.
Hide   Copy Code
<div ng-controller="Customer">
<input type=text id="CustomerName"  ng-model="CustomerName"/><br />
<input type=text id="CustomerCode"  ng-model="CustomerCode"/>
</div>

4. What are expressions in Angular?
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.
Hide   Copy Code
{{1+1}}
The below expression multiplies quantity and cost to get the total value.
Hide   Copy Code
The value total cost is {{ quantity * cost }}
The below expression displays a controller scoped variable.
Hide   Copy Code
<div ng-controller="CustomerVM">
The value of Customer code is {{CustomerCode}}
</div>
The value of Customer code is {{CustomerCode}}

5. How can we initialize Angular application data?
We can use “ng-init” directive to achieve the same. You can see in the below example we have used “ng-init” directive to initialize the “pi” value.
Hide   Copy Code
<body ng-app="myApp" ng-init="pi=3.14">
The value of pi is {{pi}}
</body>

6. Explain $scope in Angular?
“$scope” is an object instance of a controller. “$scope” object instance get’s created when “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 “ControllerName” variable.
Hide   Copy Code
function Function1($scope)
{
$scope.ControllerName = "Function1";       
}
function Function2($scope)
{
$scope.ControllerName = "Function2";
}
Now to attach the above controllers to HTML UI we need to use “ng-controller” directive. For instance you can see in the below code snippet how “ng-controller” directive attaches “function1” with “div1” tag and “function2” with “div2” tag.
Hide   Copy Code
<div id=&rdquo;div1&rdquo; ng-controller="Function1">
Instance of {{ControllerName}} created
</div>
<div id=&rdquo;div2&rdquo; ng-controller="Function2">
Instance of {{ControllerName}} created
</div>
So this is what happens internally. Once the HTML DOM is created Angular parser starts running on the DOM and following are the sequence of events:-
The parser first finds “ng-controller” directive which is pointing to “Function1”. He creates a new instance of “$scope” object and connects to the “div1” UI.
The parser then starts moving ahead and encounters one more “ng-controller” directive which is pointing to “Function2”. He creates a new instance of “$scope” object and connects to the “div2” UI.
Now once the instances are created, below is a graphical representation of the same. So the “DIV1” HTML UI is binded with “function1” $scope instance and the “DIV2” HTML UI is binded with “function2” $scope instance. In other words now anything changes in the $scope object the UI will be updated and any change in the UI will update the respective $scope object.

7. What is “$rootScope” and how is it related with “$scope”?
“$rootScope” is a parent object of all “$scope” angular objects created in a web page.
Let us understand how Angular does the same internally. Below is 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.
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 rootscope 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
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 it then attaches to “$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.
Hide   Copy Code
<script language="javascript">
function Function1($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("Function1", Function1); // Registering the VM
    app.controller("Function2", Function2);
</script>
Below is the HTML code for the same. You can we have attached “Function1” and “Function2” two times with “ng-controller” which means four instances will be created.
Hide   Copy Code
<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>
Above is 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.

8. Do I need Jquery for Angular?
No , you do not need Jquery for Angular. It’s independent of Jquery.

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

10. Explain compile and link phase?
At the heart Angular framework is a parser. A parser which parses the Angular directives and render’s HTML output.
Angular parser works in 3 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.
Now the above angular parsing is not so simple as it looks to be. It occurs in two phases “Compile” and “Link”. Firs the compile phase occurs then the link phase.
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.

11. How do we make HTTP get and post calls in Angular?
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.
Hide   Copy 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 needs atleast three things:-
First what is the kind of call “POST” or “GET”.
Second 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.
Hide   Copy Code
$http({ method: "GET", url: "http://localhost:8438/SomeMethod"    }).success(function (data, status, headers, config)
{
// Here goes code after success
}

12. How do we pass data using HTTP POST in Angular ?
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.
Hide   Copy Code
Var myData = {};
myData.CustomerName = &ldquo;Test&rdquo;;
$http({ method: "POST",
                data: myData,
                url: "http://www.xyz.com"})
                .success(function (data, status, headers, config)
                {
                  // Here goes code after success
                }

13. What is dependency injection and how does it work in Angular?
Dependency injection is a process where we inject the dependent objects rather than consumer creating the objects. DI is everywhere in Angular or we can go one step ahead and say Angular cannot work without DI.
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 rather Angular injects these objects.
Hide   Copy Code
function CustomerController($scope,$http)
{
// your consumer would be using the scope and http objects
}

14. How does DI benefit in Angular?
There are two big benefits of DI: - Decoupling and Testing.
Let’s first start with Decoupling. Consider your application has a logger functionality which helps to log errors , warning etc in some central place. This central place can be a file, event viewer, database etc.
Hide   Copy Code
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 who wants to use the “Logger” classes. Now which “Logger” class to use depends on configuration.
So the code of “Customer” is something as shown below. So depending on the configuration “Customer” class either creates “FileLogger” or it creates “EventLogger” object.
Hide   Copy Code
function Customer($scope, Logger)
{
        $scope.Logger = {};
        if (config.Loggertype = "File")
{
            $scope.Logger = new FileLogger();
        }
        else
{
            $scope.Logger = new EventLogger();
        }
}
But with DI our code becomes something as shown below. The “Customer” class says he is not worried from where the “Logger” object comes and which type of “Logger” objects are needed .He just wants to use the “Logger” object.
Hide   Copy Code
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 DI is testing. Let’s say you want to test the “Customer” class and you do not have 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 DI.

15. What are services in Angular?
Service helps to implement dependency injection. For instance let’s say we have the below “Customer” class who needs “Logger” object. Now “Logger” object can be of “FileLogger” type or “EventLogger” type.
Hide   Copy Code
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.
Hide   Copy Code
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.

16. Are Service object instances global or local?
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.
Hide   Copy Code
function HitCounter()
{
       var i = 0;
        this.Hit = function ()
        {
            i++;
            alert(i);
        };
}
This “HitCounter” class object is injected in “MyClass” class as shown in the below code.
Hide   Copy Code
function MyClass($scope, HitCounter)
{
                $scope.HitCounter = HitCounter;
}
Below code advises the Angular framework to inject “HitCounter” class instance in the “MyClass” class. Read the last line of the below code specially which says to inject the inject the “HitCounter” instance.
Hide   Copy Code
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 twodiv tag’s as shown in the below figure.
So two instances of “MyClass” will be created. When the first instance of “MyClass” is created a “HitCounter” object instance is created and injected in to “MyClass” first instance.
When the second instance of “MyClass” is created the same “HitCounter” object instance is injected in to second instance of “MyClass”.
Again I repeat the same instance is injected in to the second instance, new instances are not created.
If you execute the above code you will see counter values getting incremented even if you are coming through different controller instances.

17. What is a Factory in Angular?
“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 likelaptops,desktops, tablets etc.
Now the process of manufacturing the computer products are same with slight variation. To manufacture any computer we need processor, RAM and hard disk. But depending on what kind of final case packing is the final product shapes.
That’s what the use of Factory in Angular.
For example see the below code we have a “Customer”, “Phone” and “Address” class.
Hide   Copy Code
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 “Address” collection inside it.
Or must be we would like to create “Customer” object with “Phone” objects inside it.
Or must be “Customer” object with both “Phone” and “Address” objects.
In other words we would like to have different permutation and combination to create different types of “Customer” objects.
So let’s start from bottom. Let’s create two factory function’s one which creates “Address” object and the other which creates “Phone” objects.

Hide   Copy Code
functionCreateAddress()
{
var add = new Address();
return add;
}
functionCreatePhone()
{
var phone =  new Phone();
return phone;
}
Now let’s create a main factory function which uses the above two small factory functions and gives us all the necessary permutation and combination.
In the below factory you can see we have three functions:-
“CreateWithAddress” which creates “Customer” with “Address” objects inside it.
“CreateWithPhone” which creates “Customer” object with “Phone” objects inside it.
“CreateWithPhoneAddress” which creates “Customer” object with aggregated “Phone” and “Address” objects.
Hide   Copy Code
function CreateCustomer() {
return {
CreateWithAddress: function () {
varcust = new Customer();
cust.Address = CreateAddress();
returncust;
            },
CreateWithPhone: function () {
varcust = new Customer();
cust.Phone = {};
cust.Phone = CreatePhone();
returncust;
            }
            ,
CreateWithPhoneAddress: function () {
debugger;
varcust = new Customer();
cust.Phone = CreatePhone();
cust.Address = CreateAddress();
returncust;
            }
        }
    }
Below is a simple “CustomerController” which takes “CustomerFactory” as the input. Depending on “TypeOfCustomer” it creates with “Address” , “Phones” or both of them.
Hide   Copy Code
functionCustomerController($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.
Hide   Copy Code
var app = angular.module("myApp", []); // creating a APP
app.controller("CustomerController", CustomerController); // Register the VM
app.factory("Customerfactory", CreateCustomer);
So if we consume the “CustomerController” in UI , depending on situation it creates different flavors of “Customer” object. You can in the below code we have three different “DIV” tags and depending on the “TypeofCustomer” we are displaying data.

18. What is the difference between Factory and Service?
“Factory” and “Service” are different ways of doing DI (Dependency injection) in angular. Please read the previous question to understand what is DI.
So when we define DI using “service” as shown in the code below. This creates a new GLOBAL instance of the “Logger” object and injects it in to the function.
Hide   Copy Code
app.service("Logger", Logger); // Injects a global object
When you define DI using a “factory” it does not create a instance. It just passes the method and later the consumer internally has to make calls to the factory for object instances.

Hide   Copy Code
app.factory("Customerfactory", CreateCustomer);
Below is a simple image which shows visually how DI process for “Service” is different than “Factory”.
 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.

19. How are validations implemented in Angular?
Angular leverages HTML 5 validations and new form element types to implement validation.
For instance below is a simple form which has two text boxes. We have used HTML 5 “required” validation attribute and a form element of type “email”.
Hide   Copy Code
<form name="frm1" id="frm1" >
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
Email
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 below browser screen shot.
Angular leverages HTML 5 validation attributes and new HTML 5 form elements. Now if we want Angular to handle validation we need first stop HTML 5 to do validation. So for that the first step is to specify “novalidate” attribute on the form tag.
Hide   Copy Code
<form name="frm1" 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 UI , 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”.
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-disabled” attribute which is set via the “$Valid” 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’s false it should disable the button.
Hide   Copy Code
<form name="frm1" 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="!(frm1.$valid)"/>
</form>
Note :- “Name” is needed for the validations to work.

20. How to check error validation for a specific field?
To check for a specific field you need to use the below DOM code.
Hide   Copy Code
!frm1.CustomerName.$valid

21. What does SPA (Single page application) mean?
SPA is a concept where rather loading pages from the server by doing post backs we create a single shell page or master page and load the webpages inside that master page.
How can we implement SPA with Angular?
By using Angular routes.

22. How to implement routing in Angular?
Implementing Angular route is a five step process: -
Step 1: - Add the “Angular-route.js” file to your view.
Hide   Copy Code
<script src="~/Scripts/angular-route.js"></script>
Step 2: - Inject “ngroute” functionality while creating Angular app object.
Hide   Copy Code
var app = 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.
Hide   Copy Code
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 hyper link 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.
Hide   Copy Code
Home
Search
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.
Hide   Copy Code
So if we summarize angular routing is a three step process (Below is 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: - Router provider scans the URL and loads the view in the place holder defined by “ng-view” attribute.

23. How can we create a custom directive in Angular?
Till now we have looked in to predefined 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.
Hide   Copy Code
<div id=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 copy right directive and it returns a copy right text.
Please note “app” is an angular application object which has been explained in the previous sections.
Hide   Copy Code
app.directive('companyCopyRight', function ()
{
return
{
        template: '@CopyRight questpond.com '
 };
});
The above custom directive can be later used in elements as shown in below code.
Hide   Copy Code
<div ng-controller="CustomerViewModel">
<div company-copy-right></div>
</div>

24. What kind of naming conventions is used for custom directives?
For angular custom directive the best practice is to follow camel casing and that also with atleast 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”.
Hide   Copy Code
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.
Hide   Copy Code
<div company-copy-right></div>
If you are making a one letter prefix like “copyright” it’s 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 tag’s.

25. What are the different custom directive types in AngularJS?
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 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.
Hide   Copy Code
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.
Hide   Copy Code
<userinfo></userinfo>
If you try to use it at an attribute level as shown in the below code it will not work.
Hide   Copy Code
<div userinfo></div>
So “E” for element, “A” for attribute, “C” for CSS and “M” for comments.

26. What if I want custom directives to be applied on element as well as attributes ?
Hide   Copy Code
directive.restrict = 'EA';

27. Can I set an Angular directive template to a HTML web page?
Yes, you can set template to page directly by using “templateUrl” property of the directive as shown in the code snippet below.
Hide   Copy Code

directive.templateUrl = "/templates/footer.html";

Angular JS Qes & Ans PART-2

1.what is angular JS
AngularJS is a framework to build large scale and high performance web application while keeping them as easy-to-maintain. Following are the features of AngularJS framework.
  • AngularJS is a powerful JavaScript based development framework to create RICH Internet Application RIA.
  • AngularJS provides developers options to write client side application usingJavaScript in a clean MVC ModelViewController way.
  • Application written in AngularJS is cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser.
  • AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache License version 2.0.
2.What is data binding in AngularJS?
Data binding is the automatic synchronization of data between model and view components. ng-model directive is used in data binding.

3.What is scope in AngularJS?
Scopes are objects that refer to the model. They act as glue between controller and view.

4.What are the controllers in AngularJS?
Controllers are JavaScript functions that are bound to a particular scope. They are the prime actors in AngularJS framework and carry functions to operate on data and decide which view is to be updated to show the updated model based data.

5.What are the services in AngularJS?
AngularJS come with several built-in services. For example $http service is used to make XMLHttpRequests (Ajax calls). Services are singleton objects which are instantiated only once in app.

6.What are the filters in AngularJS?
Filters select a subset of items from an array and return a new array. Filters are used to show filtered items from a list of items based on defined criteria.

7.Explain directives in AngularJS.
Directives are markers on DOM elements suchaselements,attributes,css,andmore. These can be used to create custom HTML tags that serve as new, custom widgets. AngularJS has built-in directives ng−bind,ng−model,etc to perform most of the task that developers have to do.

8.Explain templates in AngularJS.
Templates are the rendered view with information from the controller and model. These can be a single file likeindex.html or multiple views in one page using "partials".

9.What is routing in AngularJS?
It is concept of switching views. AngularJS based controller decides which view to render based on the business logic.

10.What is deep linking in AngularJS?
Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state.

11.What are the advantages of AngularJS?
Following are the advantages of AngularJS.
  • AngularJS provides capability to create Single Page Application in a very clean and maintainable way.
  • AngularJS provides data binding capability to HTML thus giving user a rich and responsive experience.
  • AngularJS code is unit testable.
  • AngularJS uses dependency injection and make use of separation of concerns.
  • AngularJS provides reusable components.
  • With AngularJS, developer writes less code and gets more functionality.
  • In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing.
  • AngularJS applications can run on all major browsers and smart phones including Android and iOS based phones/tablets.

12.What are the disadvantages of AngularJS?
Following are the disadvantages of AngularJS.
  • Not Secure − Being JavaScript only framework, application written in AngularJS are not safe. Server side authentication and authorization is must to keep an application secure.
  • Not degradable − If your application user disables JavaScript then user will just see the basic page and nothing more.
13.Which are the core directives of AngularJS?
Following are the three core directives of AngularJS.
  • ng-app − This directive defines and links an AngularJS application to HTML.
  • ng-model − This directive binds the values of AngularJS application data to HTML input controls.
  • ng-bind − This directive binds the AngularJS Application data to HTML tags.
14.Explain AngularJS boot process.
When the page is loaded in the browser, following things happen:
  • HTML document is loaded into the browser, and evaluated by the browser. AngularJS JavaScript file is loaded; the angular global object is created. Next, JavaScript which registers controller functions is executed.
  • Next AngularJS scans through the HTML to look for AngularJS apps and views. Once view is located, it connects that view to the corresponding controller function.
  • Next, AngularJS executes the controller functions. It then renders the views with data from the model populated by the controller. The page gets ready.

15. What is MVC?
Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three parts:
  • Model − It is the lowest level of the pattern responsible for maintaining data.
  • View − It is responsible for displaying all or a portion of the data to the user.
  • Controller − It is a software Code that controls the interactions between the Model and View.

16.Explain ng-app directive.
ng-app directive defines and links an AngularJS application to HTML. It also indicate the start of the application.

17.Explain ng-model directive.
ng-model directive binds the values of AngularJS application data to HTML input controls. It creates a model variable which can be used with the html page and within the container controlforexample,div having ng-app directive.

18.Explain ng-bind directive.
ng-bind directive binds the AngularJS Application data to HTML tags. ng-bind updates the model created by ng-model directive to be displayed in the html tag whenever user input something in the control or updates the html control's data when model data is updated by controller.

19.Explain ng-controller directive.
ng-controller directive tells AngularJS what controller to use with this view. AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter which refers to the application/module that controller is to control.

20.How AngularJS integrates with HTML?
AngularJS being a pure javaScript based library integrates easily with HTML.
Step 1 − Include angularjs javascript libray in the html page
<head>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
Step 2 − Point to AngularJS app
Next we tell what part of the HTML contains the AngularJS app. This done by adding the ng-appattribute to the root HTML element of the AngularJS app. You can either add it to html element orbody element as shown below:
<bodyng-app="myapp">
</body>

21.Explain ng-init directive.
ng-init directive initializes an AngularJS Application data. It is used to put values to the variables to be used in the application.

22.Explain ng-repeat directive.
ng-repeat directive repeats html elements for each item in a collection.

23.What are AngularJS expressions?
Expressions are used to bind application data to html. Expressions are written inside double braces like {{ expression}}. Expressions behave in same way as ng-bind directives. AngularJS application expressions are pure JavaScript expressions and outputs the data where they are used.

24.Explain uppercase filter.
Uppercase filter converts a text to upper case text.
In below example, we've added uppercase filter to an expression using pipe character. Here we've added uppercase filter to print student name in all capital letters.
Enter first name:<input type ="text" ng-model ="student.firstName">
Enterlast name:<input type ="text" ng-model ="student.lastName">
NameinUpperCase:{{student.fullName()| uppercase}}

25. Explain lowercase filter.
Lowercase filter converts a text to lower case text.
In below example, we've added lowercase filter to an expression using pipe character. Here we've added lowercase filter to print student name in all lowercase letters.
Enter first name:<input type ="text" ng-model ="student.firstName">
Enterlast name:<input type ="text" ng-model ="student.lastName">
NameinUpperCase:{{student.fullName()| lowercase}}

26. Explain currency filter.
Currency filter formats text in a currency format.
In below example, we've added currency filter to an expression returning number using pipe character. Here we've added currency filter to print fees using currency format.
Enter fees:<input type ="text" ng-model ="student.fees">
fees:{{student.fees | currency}}

27. Explain filter.
Filter is used to filter the array to a subset of it based on provided criteria.
In below example, to display only required subjects, we've used subjectName as filter.
Enter subject:<input type ="text" ng-model ="subjectName">
Subject:
<ul>
<li ng-repeat ="subject in student.subjects | filter: subjectName">
{{ subject.name +', marks:'+ subject.marks }}
</li>
</ul>



28. Explain orderby filter.
Orderby filter orders the array based on provided criteria.
In below example, to order subjects by marks, we've used orderBy marks.
Subject:
<ul>
<li ng-repeat ="subject in student.subjects | orderBy:'marks'">
{{ subject.name +', marks:'+ subject.marks }}
</li>
</ul>

29. Explain ng-disabled directive.
ng-disabled directive disables a given control.
In below example, we've added ng-disabled attribute to a HTML button and pass it a model. Then we've attached the model to an checkbox and can see the variation.
<inputtype="checkbox"ng-model="enableDisableButton">Disable Button
<buttonng-disabled="enableDisableButton">Click Me!</button>

30.Explain ng-show directive.
ng-show directive shows a given control.
In below example, we've added ng-show attribute to a HTML button and pass it a model. Then we've attached the model to a checkbox and can see the variation.
<inputtype="checkbox"ng-model="showHide1">Show Button
<buttonng-show="showHide1">Click Me!</button>

31.Explain ng-hide directive.
ng-hide directive hides a given control.
In below example, we've added ng-hide attribute to a HTML button and pass it a model. Then we've attached the model to a checkbox and can see the variation.
<inputtype="checkbox"ng-model="showHide2">Hide Button
<buttonng-hide="showHide2">Click Me!</button>

32. Explain ng-click directive.
ng-click directive represents a AngularJS click event.
In below example, we've added ng-click attribute to a HTML button and added an expression to updated a model. Then we can see the variation.
<p>Total click: {{ clickCounter }}</p></td>
<buttonng-click="clickCounter = clickCounter + 1">Click Me!</button>

33. How angular.module works?
angular.module is used to create AngularJS modules along with its dependent modules. Consider the following example:
var mainApp = angular.module("mainApp",[]);
Here we've declared an application mainApp module using angular. module function. We've passed an empty array to it. This array generally contains dependent modules declared earlier.

34. How to validate data in AngularJS?
AngularJS enriches form filling and validation. We can use dirty and invalid flags to do the validations in seamless way. Use no validate with a form declaration to disable any browser specific validation.
Following can be used to track error.
  • $dirty − states that value has been changed.
  • $invalid − states that value entered is invalid.
  • $error − states the exact error.

35. Explain ng-include directive.
Using AngularJS, we can embed HTML pages within a HTML page using ng-include directive.
<divng-app=""ng-controller="studentController">
<divng-include="'main.htm'"></div>
<divng-include="'subjects.htm'"></div>
</div>

36. How to make an Ajax call using Angular JS?
AngularJS provides httpcontrolwhichworksasaservicetomakeajaxcalltoreaddatafromtheserver.Theservermakesadatabasecalltogetthedesiredrecords.AngularJSneedsdatainJSONformat.Oncethedataisready,http can be used to get the data from server in the following manner:
function studentController($scope,$http){
var url ="data.txt";
   $http.get(url).success(function(response){
      $scope.students = response;
});
}

37. What is use of $routeProvider in AngularJS?
$routeProvider is the key service which set the configuration of urls, maps them with the corresponding html page or ng-template, and attaches a controller with the same.

38. What is $rootScope?
Scope is a special JavaScript object which plays the role of joining controller with the views. Scope contains the model data. In controllers, model data is accessed via scopeobject.rootScope is the parent of all of the scope variables.

39. What is scope hierarchy in AngularJS?
Scopes are controllers specific. If we define nested controllers then child controller will inherit the scope of its parent controller.
<script>
var mainApp = angular.module("mainApp",[]);

      mainApp.controller("shapeController",function($scope){
         $scope.message ="In shape controller";
         $scope.type ="Shape";
});
              
      mainApp.controller("circleController",function($scope){
         $scope.message ="In circle controller";
});
</script>
Following are the important points to be considered in above example.
  • We've set values to models in shape Controller.
  • We've overridden message in child controller circle Controller. When "message" is used within module of controller circle Controller, the overridden message will be used.

40. What is a service?
Services are JavaScript functions and are responsible to do specific tasks only. Each service is responsible for a specific task for example; http is used to make Ajax call to get the server data. Route is used to define the routing information and so on. Inbuilt services are always prefixed with $ symbol.

41. What is service method?
Using service method, we define a service and then assign method to it. We've also injected an already available service to it.
mainApp.service('CalcService',function(MathService){
this.square =function(a){
returnMathService.multiply(a,a);
               }
});

42. What is factory method?
Using factory method, we first define a factory and then assign method to it.
var mainApp = angular.module("mainApp",[]);
mainApp.factory('MathService',function(){
var factory ={};
                              
   factory.multiply =function(a, b){
return a * b
}
return factory;
});

43. What are the differences between service and factory methods?
Factory method is used to define a factory which can later be used to create services as and when required whereas service method is used to create a service whose purpose is to do some defined task.

44. Which components can be injected as a dependency in AngularJS?
AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.
  • value
  • factory
  • service
  • provider
  • constant

45. What is provider?
Provider is used by AngularJS internally to create services, factory etc. during config phase. phase during which AngularJS bootstraps itself. Below mention script can be used to create MathService that we've created earlier. Provider is a special factory method with a method get which is used to return the value/service/factory.
//define a module
var mainApp = angular.module("mainApp",[]);
...
//create a service using provider which defines a method square to return square of a number.
mainApp.config(function($provide){
   $provide.provider('MathService',function(){
              
this.$get =function(){
var factory ={};
         factory.multiply =function(a, b){
return a * b;
}
return factory;
};
                              
});
});

46. What is constant?
Constants are used to pass values at config phase considering the fact that value cannot be used to be passed during config phase.
mainApp.constant("configParam", "constant value");

47. Is AngularJS extensible?
Yes! In AngularJS we can create custom directive to extend AngularJS existing functionalities.
Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using "directive" function. A custom directive simply replaces the element for which it is activated.
AngularJS application during bootstrap finds the matching elements and does one time activity using its compile method of the custom directive then process the element using link method of the custom directive based on the scope of the directive.

48. On which types of component can we create a custom directive?
AngularJS provides support to create custom directives for following type of elements.
  • Element directives − Directive activates when a matching element is encountered.
  • Attribute − Directive activates when a matching attribute is encountered.
  • CSS − Directive activates when a matching css style is encountered.
  • Comment − Directive activates when a matching comment is encountered.

49. What is internationalization?
Internationalization is a way to show locale specific information on a website. For example, display content of a website in English language in United States and in Danish in France.

50. How to implement internationalization in AngularJS?
AngularJS supports inbuilt internationalization for three types of filters currency, date and numbers. We only need to incorporate corresponding js according to locale of the country. By default it handles the locale of the browser. For example, to use Danish locale, use following script

<scriptsrc="https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"></script>