Learn Angular JS
This document is for Angular Js version (1.X) :-
Bascis of Angular Js : -
Created by Misko Hevery in 2009
Open source supported by Google
Definition: - HTML enhanced for web apps! AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag. AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions
Various Data binding frameworks:
* Facilitate building single page application
- Page Never reloads
- No server side page rendering
* Built on Model, View , Controller concept
* Provides solution for
- Routing - handling updates to the URL hash fragment
- Templating - dynamically creating and updating HTML based on templates and modules
- Data binding - synchronise the model and use interface
* Top data binding frameworks today
- Angular.js
- Knockout
- Ember
- JsViews
- Can.js
- Ractive
Angular js fundamental libraries
Underscore
Backbonejs
Jquery
AMD - Asynchronus Module Definition
Promises
Handlebars - templating engine
cdn = content distribution network
ng-app -
ng-model - The ngModel directive binds an input , select , textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive. ngModel is responsible for: Binding the view into the model, which other directives such as input , textarea or select require.ng-repeat - used to display the repeated data eg. display select dropdown
ng-controller -
ng-src - set source after the model load/after template loads this is to avoid network error
$scope - is model binded for function
$routeProvider
$http - is angulars dependency injection mechanism, angular gives you http module, $http is a wrapper for xmlhttp request. $http.get, $http.post etc.
module
controller
factory
http
config
filter
currency
Single Page Application
One page only, no page loads.
Information fetched on the fly using XMLHTTPRequest
AJAX
Related concept: "Server Side Push"
Comet (programming) (also known as Reverse Ajax) long polling XMLHTTPRequest
WebSocket full-duplex communications channels over a single TCP connection
Socket.io Node.js library for WebSocket
Fragment Identifier used for routing
index.html#pageA
index.html#pageB
Reference :
https://github.com/curran/screencasts/tree/gh-pages/introToAngular
https://github.com/curran/screencasts/tree/gh-pages/navigation
Angular js videos tutorial for beginners :
https://www.youtube.com/watch?v=TRrL5j3MIvo
https://www.youtube.com/watch?v=6J08m1H2BME
==================================================
* AngularJS provides capability to create Single Page Application.
* Provides data binding capability to HTML thus giving user a rich and responsive experience.
* Execution : -
When the page is loaded in the browser, following things happen:
1. 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.
2. 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.
3. Next, AngularJS executes the controller functions. It then renders the views with data from the model populated by the controller. The page is now ready.
Important parts of Angular JS : -
Following diagram explains the important parts of Angular JS,
An AngularJS application consists of following three important parts :-
1. ng-app : This directive defines and links an AngularJS application to HTML.
2. ng-model : This directive binds the values of AngularJS application data to HTML input controls.
3. ng-bind : This directive bidns the AngularJS Application data to HTML tags.
Steps to create AngularJS Application : -
Step 1: Load framework
Being a pure JavaScript framework, It can be added using <Script> tag.
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
Step 2: Define AngularJS Application using ng-app directive
<div ng-app="">
...
</div>
Step 3: Define a model name using ng-model directive
<p>Enter your Name: <input type="text" ng-model="name"></p>
Step 3: Bind the value of above model defined using ng-bind directive.
<p>Hello <span ng-bind="name"></span>!</p>
How AngularJS integrates with HTML : -
1. ng-app directive indicates the start of AngularJS application.
2. ng-model directive then creates a model variable named "name" which can be used with the html page and within the div having ng-app directive.
3. ng-bind then uses the name model to be displayed in the html span tag whenever user input something in the text box.
4. Closing</div> tag indicates the end of AngularJS application.
Example : -
Now let us write a simple example using AngularJS library. Let us create an HTML file myfirstexample.html as below:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.17/angular.min.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="HelloController" >
<h2>Welcome {{helloTo.title}} to the world of Tutorialspoint!</h2>
</div>
<script>
angular.module("myapp", [])
.controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
});
</script>
</body>
</html>
Include AngularJS
We have included the AngularJS JavaScript file in the HTML page so we can use AngularJS:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
Point to AngularJS app
Next we tell what part of the HTML contains the AngularJS app. This done by adding the ng-app attribute to the root HTML element of the AngularJS app. You can either add it to html element or body element as shown below:
<body ng-app="myapp">
</body>
View
The view is this part:
<div ng-controller="HelloController" >
<h2>Welcome {{helloTo.title}} to the world of Tutorialspoint!</h2>
</div>
ng-controller tells AngularJS what controller to use with this view. helloTo.title tells AngularJS to write the "model" value named helloTo.title to the HTML at this location.
Controller
The controller part is:
<script>
angular.module("myapp", [])
.controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
});
</script>
This code registers a controller function named HelloController in the angular module named myapp. We will study more about modules and controllers in their respective chapters. The controller function is registered in angular via the angular.module(...).controller(...) function call.
The $scope parameter passed to the controller function is the model. The controller function adds a helloTo JavaScript object, and in that object it adds a title field.
AngularJS directives are used to extend HTML : -
These are special attributes starting with ng- prefix. We're going to discuss following directives,
1. ng-app - This directive starts an AngularJS Application.
2. ng-init - This directive initializes application data.
3. ng-model - This directive defines the model that is variable to be used in AngularJS.
4. ng-repeat - This directive repeats html elements for each item in a collection.
Learn to code in Angular js
=========================================================================
Technical practice : -
# angularjs - create controller and factory function
In html file
<html>
<script src="angularjs.js">
<script src="common.js">
<script src="home.js">
<body>
<div ng-app='MyApp' ng-controller="HomepageCtrl">
<a href="javascript:;" ng-click='likeMedia($index, mediaId, personId)'>Like</a>
<a href="javascript:;" ng-click='loadMore()'>Load More</a>
</div>
</body>
</html>
In common.js
var commonModule = angular.module("CommonModule", []);
commonModule.factory('LikeUnlikeFactory', function ($http) {
return {
likeMedia: function (mediaId, personId) {
var req = {
method: 'POST',
url: 'http://site.com/likemedia',
headers: {
'Content-Type': 'application/json'
},
data: {'actionname': 'like', 'mediaid': mediaId, 'personid': personId}
};
return $http(req).then(function (response) {
return response;
});
}
});
In home.js
//module
var app = angular.module("MyApp", ['CommonModule']);
//factory function
app.factory('Item', function ($http) {
return {
get: function (limit) {
return "item list";
}
};
});
//controller
app.controller('HomepageCtrl', function ($scope, Item, LikeUnlikeFactory) {
$scope.loadMore = function () {
Item.get('5').then(function (response) {
alert(response);
});
};
$scope.likeMedia = function (index, mediaId, personId) {
LikeUnlikeFactory.likeMedia(mediaId, personId).then(function (response) {
alert(response);
});
};
});
=========================================================================
· Use novalidate on the form to disable HTML validation. (e.g. <form novalidate>)
· Instead of HTML validations use AngularJS validation directives. (e.g. <input ng-required="true" ng-minlength="5" />, <button type="submit" ng-click="AddUser()" >)
<button type="submit" ng-disabled="!nameofform.$valid" ng-click="AddUser()" class="form-control btn btn-info">
example: -
<input type="text" ng-required="true" name="name" ng-model="userfullName" class="form-control" placeholder="Full Name">
<span class="help-block" ng-show="nameofform.name.$invalid && !nameofform.name.$pristine"> You name is required.</span>
example: -
<div id="name-group" class="form-group-lg" ng-class="{ 'has-error' : adduser.name.$invalid && !adduser.name.$pristine }">
<input type="text" ng-required="true" name="name" ng-model="userfullName" class="form-control" placeholder="Full Name">
<span class="help-block" ng-show="nameofform.name.$invalid && !nameofform.name.$pristine"> You name is required.</span>
</div>
example: -
if ($scope.adduser.$valid) {
alert('all inputs are valid ');
}
else {
alert('all inputs are not valid ');
}
=========================================================================
Technical practice : -
# angularjs - create controller and factory function
In html file
<html>
<script src="angularjs.js">
<script src="common.js">
<script src="home.js">
<body>
<div ng-app='MyApp' ng-controller="HomepageCtrl">
<a href="javascript:;" ng-click='likeMedia($index, mediaId, personId)'>Like</a>
<a href="javascript:;" ng-click='loadMore()'>Load More</a>
</div>
</body>
</html>
In common.js
var commonModule = angular.module("CommonModule", []);
commonModule.factory('LikeUnlikeFactory', function ($http) {
return {
likeMedia: function (mediaId, personId) {
var req = {
method: 'POST',
url: 'http://site.com/likemedia',
headers: {
'Content-Type': 'application/json'
},
data: {'actionname': 'like', 'mediaid': mediaId, 'personid': personId}
};
return $http(req).then(function (response) {
return response;
});
}
});
In home.js
//module
var app = angular.module("MyApp", ['CommonModule']);
//factory function
app.factory('Item', function ($http) {
return {
get: function (limit) {
return "item list";
}
};
});
//controller
app.controller('HomepageCtrl', function ($scope, Item, LikeUnlikeFactory) {
$scope.loadMore = function () {
Item.get('5').then(function (response) {
alert(response);
});
};
$scope.likeMedia = function (index, mediaId, personId) {
LikeUnlikeFactory.likeMedia(mediaId, personId).then(function (response) {
alert(response);
});
};
});
=========================================================================
Angular js Tips on Validations
//To include html source and assign the same to particular div it need to use ng-include="'filesource.html'" directive
Note: - do not forget to remember double quote and single quote position
<div ng-include="'footer.html'"></div>
<div ng-include="'footer.html'"></div>
//To assign some source or html from $scope it need to use ng-include tag with src attribute
<ng-include src="pageSource"></ng-include>
//AngularJS validation properties
While working with AngularJS validation, the following are important properties:
- $valid - returns true if input is valid
- $invalid - returns true if input is valid
- $pristine - returns true if input has not been used yet
- $dirty - returns true if input has beed used
- $touched - returns true if input has beed blurred
Property Class Description
$valid ng-valid Boolean Tells whether an item is currently valid based on the rules you placed.
$invalid ng-invalid Boolean Tells whether an item is currently invalid based on the rules you placed.
$pristine ng-pristine Boolean True if the form/input has not been used yet.
$dirty ng-dirty Boolean True if the form/input has been used.
$touched ng-touched Boolean True if the input has been blurred.
example:
<input ng-model="{ string }" name="{ string }" required ng-required="{ boolean }" ng-minlength="{ number }" ng-maxlength="{ number }" ng-pattern="{ string }" ng-change="{ string }"> </input>
- $valid - returns true if input is valid
- $invalid - returns true if input is valid
- $pristine - returns true if input has not been used yet
- $dirty - returns true if input has beed used
- $touched - returns true if input has beed blurred
Property Class Description
$valid ng-valid Boolean Tells whether an item is currently valid based on the rules you placed.
$invalid ng-invalid Boolean Tells whether an item is currently invalid based on the rules you placed.
$pristine ng-pristine Boolean True if the form/input has not been used yet.
$dirty ng-dirty Boolean True if the form/input has been used.
$touched ng-touched Boolean True if the input has been blurred.
example:
<input ng-model="{ string }" name="{ string }" required ng-required="{ boolean }" ng-minlength="{ number }" ng-maxlength="{ number }" ng-pattern="{ string }" ng-change="{ string }"> </input>
//error messages
<!-- load ngmessages -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-messages.js"></script>
angular.module('app', ['ngMessages']);
<div class="help-block" ng-messages="userForm.name.$error" ng-if="userForm.name.$touched">
<p ng-message="minlength">Your name is too short.</p>
<p ng-message="maxlength">Your name is too long.</p>
<p ng-message="required">Your name is required.</p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-messages.js"></script>
angular.module('app', ['ngMessages']);
<div class="help-block" ng-messages="userForm.name.$error" ng-if="userForm.name.$touched">
<p ng-message="minlength">Your name is too short.</p>
<p ng-message="maxlength">Your name is too long.</p>
<p ng-message="required">Your name is required.</p>
</div>
//reusable messages with include message file
Here’s the messages.html file:
<p ng-message="required">This field is required</p>
<p ng-message="minlength">This field is too short</p>
<p ng-message="maxlength">This field is too long</p>
<p ng-message="required">This field is required</p>
<p ng-message="email">This needs to be a valid email</p>
Now we can use it for our email input:
<div class="help-block" ng-messages="userForm.email.$error">
<div ng-messages-include="messages.html"></div>
</div>
<p ng-message="required">This field is required</p>
<p ng-message="minlength">This field is too short</p>
<p ng-message="maxlength">This field is too long</p>
<p ng-message="required">This field is required</p>
<p ng-message="email">This needs to be a valid email</p>
Now we can use it for our email input:
<div class="help-block" ng-messages="userForm.email.$error">
<div ng-messages-include="messages.html"></div>
</div>
//default validation is htm5 validation to override html5 validation with angular js
Other option is to validate the user input only using the AngularJS directives. To work with only AngularJS validation, we need to perform the following tasks –· Use novalidate on the form to disable HTML validation. (e.g. <form novalidate>)
· Instead of HTML validations use AngularJS validation directives. (e.g. <input ng-required="true" ng-minlength="5" />, <button type="submit" ng-click="AddUser()" >)
//Disable Submit button if Form is not valid (e.g. <button type="submit" ng-disabled="!nameofform.$valid")
We can disable the submit button if the form is not valid or any of the user input is invalid. Let us use AngularJS $valid property to disable the submit button if the form is invalid:<button type="submit" ng-disabled="!nameofform.$valid" ng-click="AddUser()" class="form-control btn btn-info">
//Show the error message ($valid and $pristine)
Unlikely HTML5 validation rules, by default AngularJS validation directives does not display any error message for the invalid user input. However we can show the error message as shown in the listing below. We are using $valid and $pristine properties to display the error message:example: -
<input type="text" ng-required="true" name="name" ng-model="userfullName" class="form-control" placeholder="Full Name">
<span class="help-block" ng-show="nameofform.name.$invalid && !nameofform.name.$pristine"> You name is required.</span>
//Styling the error message and input control (e.g. <div ng-class="{ 'has-error' : adduser.name.$invalid && !adduser.name.$pristine }">)
Using the $valid and $pristine properties we can display the error message and create a style for it using the listing below:example: -
<div id="name-group" class="form-group-lg" ng-class="{ 'has-error' : adduser.name.$invalid && !adduser.name.$pristine }">
<input type="text" ng-required="true" name="name" ng-model="userfullName" class="form-control" placeholder="Full Name">
<span class="help-block" ng-show="nameofform.name.$invalid && !nameofform.name.$pristine"> You name is required.</span>
</div>
//Reading Validation properties in the Controller
In the controller, we can read whether form is valid or not using the $valid property on the form name. If all the user input is valid we will get value of $valid property true. Whether the form is valid or not can be checked in the controller as shown in the listing below:example: -
if ($scope.adduser.$valid) {
alert('all inputs are valid ');
}
else {
alert('all inputs are not valid ');
}
=========================================================================
//facebook connect with angular js
https://github.com/Ciul/angular-facebookhttp://plnkr.co/edit/0xpYLxMUZ4yp4ZUZ1RVK?p=preview
=========================================================================
AngularJs cookies (do not forgot to include $cookies dependency)
//get all cookies in angularjs
var cookies = $cookies.getAll();//get specific cookie
var cookie = $cookies.get('cookievarname');//set cookie variable
$cookies.put('cookievarname', 'cookievalue');//remove cokkies in angular js
var cookies = $cookies.getAll();angular.forEach(cookies, function (v, k) {
$cookies.remove(k);
});
=========================================================================
Angular js conditional statements in template file
Also ternary
<span>{{isAdded ? 'Added' : 'Add to cart'}}</span>If statement
<div ng-if="video == video.large"><!-- code to render a large video block-->
</div>
<div ng-if="video != video.large">
<!-- code to render the regular video block -->
</div>
switch statement
<div ng-switch on="video"><div ng-switch-when="video.large">
<!-- code to render a large video block-->
</div>
<div ng-switch-default>
<!-- code to render the regular video block -->
</div>
</div>
=========================================================================
START ANGULAR JS INTERVIEW QUESTIONS ANSWERS
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.
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.
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>
What are expressions in Angular?
Angular expressionsare 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}}
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>
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=”div1” ng-controller="Function1"> Instance of {{ControllerName}} created </div> <div id=”div2” 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.

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.
Do I need Jquery for Angular?
No , you do not need Jquery for Angular. It’s independent of Jquery.
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.
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.

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
}
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 = “Test”;
$http({ method: "POST",
data: myData,
url: "http://www.xyz.com"})
.success(function (data, status, headers, config)
{
// Here goes code after success
}
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
}
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.
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.
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.
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.
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.
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.

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. |
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
- 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.
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
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.
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
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.

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>
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.
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.
What if I want custom directives to be applied on element as well as attributes ?
Hide Copy Code
directive.restrict = 'EA';
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";
===========================
===========================
1) What is Angular.js?
AngularJS is a javascript framework used for creating single web page applications. It allows you to use HTML as your template language and enables you to extend HTML’s syntax to express your application’s components clearly
2) Explain what are the key features of Angular.js ?
The key features of angular.js are
- Scope
- Controller
- Model
- View
- Services
- Data Binding
- Directives
- Filters
- Testable
Scope refers to the application model, it acts like glue between application controller and the view. Scopes are arranged in hierarchical structure and impersonate the DOM ( Document Object Model) structure of the application. It can watch expressions and propagate events.
4) Explain what is services in Angular.js ?
In angular.js services are the singleton objects or functions that are used for carrying out specific tasks. It holds some business logic and these function can be called as controllers, directive, filters and so on.
5) Explain what is Angular Expression? Explain what is key difference between angular expressions and JavaScript expressions?
Like JavaScript, Angular expressions are code snippets that are usually placed in binding such as {{ expression }}
The key difference between the JavaScript expressions and Angular expressions
- Context : In Angular, the expressions are evaluated against a scope object, while the Javascript expressions are evaluated against the global window
- Forgiving: In Angular expression evaluation is forgiving to null and undefined, while in Javascript undefined properties generates TypeError or ReferenceError
- No Control Flow Statements: Loops, conditionals or exceptions cannot be used in an angular expression
- Filters: To format data before displaying it you can use filters
You can initialize a select box with options on page load by using ng-init directive
- <div ng-controller = “ apps/dashboard/account ” ng-switch
- On = “! ! accounts” ng-init = “ loadData ( ) ”>
A directive is something that introduces new syntax, they are like markers on DOM element which attaches a special behavior to it. In any Angular.js application, directives are the most important components.
Some of the commonly used directives are ng-model, ng-App, ng-bind, ng-repeat , ng-show etc.
8) Mention what are the advantages of using Angular.js ?
Angular.js has several advantages in web development.
- Angular.js supports MVS pattern
- Can do two ways data binding using Angular.js
- It has per-defined form validations
- It supports both client server communication
- It supports animations
Angular js routes enable you to create different URLs for different content in your application. Different URLs for different content enables user to bookmark URLs to specific content. Each such bookmarkable URL in Angular.js is called a route
A value in Angular JS is a simple object. It can be a number, string or JavaScript object. Values are typically used as configuration injected into factories, services or controllers. A value should be belong to an Angular.js module.
Injecting a value into an Angular.js controller function is done by adding a parameter with the same name as the value.
10) Explain what is data binding in Angular.js ?
Automatic synchronization of data between the model and view components is referred as data binding in Angular.js. There are two ways for data binding
- Data mining in classical template systems
- Data binding in angular templates
- Registering Callbacks: There is no need to register callbacks . This makes your code simple and easy to debug.
- Control HTML DOM programmatically: All the application that are created using Angular never have to manipulate the DOM although it can be done if it is required
- Transfer data to and from the UI: Angular.js helps to eliminate almost all of the boiler plate like validating the form, displaying validation errors, returning to an internal model and so on which occurs due to flow of marshalling data
- No initilization code: With angular.js you can bootstrap your app easily using services, which auto-injected into your application in Guice like dependency injection style
In angular.js the compiler during the compilation process matches text and attributes using interpolate service to see if they contains embedded expressions. As part of normal digest cycle these expressions are updated and registered as watches.
13) Mention the steps for the compilation process of HTML happens?
Compilation of HTML process occurs in following ways
- Using the standard browser API, first the HTML is parsed into DOM
- By using the call to the $compile () method, compilation of the DOM is performed. The method traverses the DOM and matches the directives.
- Link the template with scope by calling the linking function returned from the previous step
During compilation process when specific HTML constructs are encountered a behaviour or function is triggered, this function is referred as directive. It is executed when the compiler encounters it in the DOM.
Different types of directives are
- Element directives
- Attribute directives
- CSS class directives
- Comment directives
Link combines the directives with a scope and produce a live view. For registering DOM listeners as well as updating the DOM, link function is responsible. After the template is cloned it is executed.
- Pre-linking function: Pre-linking function is executed before the child elements are linked. It is not considered as the safe way for DOM transformation.
- Post linking function: Post linking function is executed after the child elements are linked. It is safe to do DOM transformation by post-linking function
An injector is a service locator. It is used to retrieve object instances as defined by provider, instantiate types, invoke methods and load modules. There is a single injector per Angular application, it helps to look up an object instance by its name.
17) Explain what is the difference between link and compile in angular.js?
- Compile function: It is used for template DOM Manipulation and collect all of the directives.
- Link function: It is used for registering DOM listeners as well as instance DOM manipulation. It is executed once the template has been cloned.
For creating the directive, factory method is used. It is invoked only once, when compiler matches the directive for the first time. By using $injector.invoke the factory method is invoked.
19) Mention what are the styling form that ngModel adds to CSS classes ?
ngModel adds these CSS classes to allow styling of form as well as control
- ng- valid
- ng- invalid
- ng-pristine
- ng-dirty
- To observer model mutations scopes provide APIs ($watch)
- To propagate any model changes through the system into the view from outside of the Angular realm
- A scope inherits properties from its parent scope, while providing access to shared model properties, scopes can be nested to isolate application components
- Scope provides context against which expressions are evaluated
DI or Dependency Injection is a software design pattern that deals with how code gets hold of its dependencies. In order to retrieve elements of the application which is required to be configured when module gets loaded , the operation “config” uses dependency injection.
These are the ways that object uses to hold of its dependencies
- Typically using the new operator, dependency can be created
- By referring to a global variable, dependency can be looked up
- Dependency can be passed into where it is required
Advantages of using Angular.js as framework are
- Supports two way data-binding
- Supports MVC pattern
- Support static template and angular template
- Can add custom directive
- Supports REST full services
- Supports form validations
- Support both client and server communication
- Support dependency injection
- Applying Animations
- Event Handlers
Each angular application consist of one root scope but may have several child scopes. As child controllers and some directives create new child scopes, application can have multiple scopes. When new scopes are formed or created they are added as a children of their parent scope. Similar to DOM, they also creates a hierarchical structure.
24) Explain what is the difference between angular.js and backbone.js?
Angular.js combines the functionalities of most of the 3rd party libraries, it supports individual functionalities required to develop HTML5 Apps. While Backbone.js do their jobs individually.
25) Who created Angular JS ?
Intially it was developed by Misko Hevery and Adam Abrons. Currently it is being developed by Google.
=================
=================
Can you please explain what is testability like in Angular?
Ans. Very testable and designed this way from ground up. It has an integrated dependency injection framework, provides mocks for many heavy dependencies (server-side communication)
Why is this project called "AngularJS"? Why is the namespace called "ng"?
Because HTML has Angular brackets and "ng" sounds like "Angular".Tell me does Angular use the jQuery library?
Yes, Angular can use jQuery if it's present in your app when the application is being bootstrapped. If jQuery is not present in your script path, Angular falls back to its own implementation of the subset of jQuery that we call jQLite.Is AngularJS a library, framework, plugin or a browser extension?
AngularJS fits the definition of a framework the best, even though it's much more lightweight than a typical framework and that's why many confuse it with a library.
AngularJS is 100% JavaScript, 100% client side and compatible with both desktop and mobile browsers. So it's definitely not a plugin or some other native browser extension.
Tell me can we use the open-source Closure Library with Angular?
Yes, you can use widgets from the Closure Library in Angular.Do you know what is Angulars performance like?
Ans. The startup time heavily depends on your network connection, state of the cache, browser used and available hardware, but typically we measure bootstrap time in tens or hundreds of milliseconds.The runtime performance will vary depending on the number and complexity of bindings on the page as well as the speed of your backend (for apps that fetch data from the backend). Just for an illustration we typically build snappy apps with hundreds or thousands of active bindings.
Tell me which browsers does Angular work with?
Ans. We run our extensive test suite against the following browsers: Safari, Chrome, Firefox, Opera, IE8, IE9 and mobile browsers (Android, Chrome Mobile, iOS Safari). See Internet Explorer Compatibility for more details in supporting legacy IE browsers.Why to choose Angular JS Javascript Framework for front-end web development?
Ans.
AngularJS is quickly becoming the dominant JavaScript framework for professional web development. With the growth and strength of HTML5 and the increasing performance in modern browsers, many JavaScript frameworks have been created to help develop rich client applications. These frameworks/libraries have given developers a huge toolkit to build enterprise complexity into client-side applications. Server side frameworks are becoming a thing of the past and being replaced with applications written in Backbone, Ember, AngularJS, Knockout, etc.
So why am I talking about AngularJS over frameworks/libraries like Backbone, Ember, or Knockout?
For me, the major points of separation in AngularJS’s favor are the following:
1. Good documentation
2. Write less code to do more
3. Backed by Google
4. Good developer community
5. Simple Data-Binding
6. Small footprint
If you’re looking for a robust, well-maintained framework for any sized project, I strongly recommend that you take a look at AngularJS. It can be downloaded for free at AngularJS.org, which also contains a wealth of information, including the full API documentation, as well as numerous examples and tutorials that cover every facet of front-end web development. Following are some reasons why to choose Angular JS Javascript Framework for front-end web development?
1. Angular JS Framework is developed by Google
Angular is built and maintained by dedicated Google engineers. This one may seem obvious, but it’s important to remember that many (not all) frameworks are made by hobbyists in the open source community. While passion and drive have forged frameworks, like Cappucino and Knockout, Angular is built and maintained by dedicated (and highly talented) Google engineers. This means you not only have a large open community to learn from, but you also have skilled, highly-available engineers tasked to help you get your Angular questions answered.
This isn’t Google’s first attempt at a JavaScript framework; they first developed their comprehensive Web Toolkit, which compiles Java down to JavaScript, and was used by the Google Wave team extensively. With the rise of HTML5, CSS3, and JavaScript, as both a front-end and back-end language, Google realized that the web was not meant to be written purely in Java.
AngularJS came about to standardize web application structure and provide a future template for how client-side apps should be developed.
Angular JS is being used by a host of applications, ranging from hobby to commercial products. Adoption of AngularJS as a viable framework for client-side development is quickly becoming known to the entire web development community.
Because AngularJS is built by Google, you can be sure that you’re dealing with efficient and reliable code that will scale with your project. If you’re looking for a framework with a solid foundation, Angular is your choice!
2. Angular JS is equipped with a lot of features
If you’re familiar with projects, like QUnit, Mocha or Jasmine, then you’ll have no trouble learning Angular’s unit-testing API.
Angular, similar to Backbone or JavaScriptMVC, is a complete solution for rapid front-end development. No other plugins or frameworks are necessary to build a data-driven web application. Here’s an overview of Angular’s stand-out features:
A) REST Easy. RESTful actions are quickly becoming the standard for communicating from the server to the client. In one line of JavaScript, you can quickly talk to the server and get the data you need to interact with your web pages. AngularJS turns this into a simple JavaScript object, as Models, following the MVVM (Model View View-Model) pattern.
B) MVVM to the Rescue! Models talk to ViewModel objects (through something called the $scope object), which listen for changes to the Models. These can then be delivered and rendered by the Views, which is the HTML that expresses your code. Views can be routed using the $routeProvider object, so you can deep-link and organize your Views and Controllers, turning them into navigable URLs. AngularJS also provides stateless controllers, which initialize and control the $scope object.
C) Data Binding and Dependency Injection. Everything in the MVVM pattern is communicated automatically across the UI whenever anything changes. This eliminates the need for wrappers, getters/setters or class declarations. AngularJS handles all of this, so you can express your data as simply as with JavaScript primitives, like arrays, or as complex as you wish, through custom types. Since everything happens automatically, you can ask for your dependencies as parameters in AngularJS service functions, rather than one giant main() call to execute your code.
D) Extends HTML. Most websites built today are a giant series of <div> tags with little semantic clarity. You need to create extensive and exhaustive CSS classes to express the intention of each object in the DOM. With Angular, you can operate your HTML like XML, giving you endless possibilities for tags and attributes. Angular accomplishes this, via its HTML compiler and the use of directives to trigger behaviors based on the newly-created syntax you write.
E) Makes HTML your Template. If you’re used to Mustache or Hogan.js, then you can quckly grasp the bracket syntax of Angular’s templating engine, because it’s just HTML. Angular traverses the DOM for these templates, which house the directives mentioned above. The templates are then passed to the AngularJS compiler as DOM elements, which can be extended, executed or reused. This is key, because, now, you have raw DOM components, rather than strings, allowing for direct manipulation and extension of the DOM tree.
F) Enterprise-level Testing. As stated above, AngularJS requires no additional frameworks or plugins, including testing. If you’re familiar with projects, like QUnit, Mocha or Jasmine, then you’ll have no trouble learning Angular’s unit-testing API and Scenario Runner, which guides you through executing your tests in as close to the actual state of your production application as possible.
These are the fundamental principles that guide AngularJS to creating an efficient, performance-driven, and maintainable front-end codebase. As long as you have a source for storing data, AngularJS can do all of the heavy lifting on the client, while providing a rich, fast experience for the end user.
3. You can learn Angular JS easily
Getting started with AngularJS is incredibly easy. With a few attributes added to your HTML, you can have a simple Angular app up in under 5 minutes!
1. Add the ng-app directive to the <html> tag so Angular knows to run on the page:
<html lang="en" ng-app>
2. Add the Angular <script> tag to the end of your <head> tag:
<head>
<script src="lib/angular/angular.js"></script>
...
</head>
3. Add regular HTML. AngularJS directives are accessed through HTML attributes, while expressions are evaluated with double-bracket notation:
<body ng-controller="ActivitiesListCtrl">
<h1>Today's activities</h1>
<ul>
<li ng-repeat="activity in activities">
{{activity.name}}
</li>
</ul>
</body>
</html>
What are the key features of AngularJS?
Ans.
Scope
The job of the Scope is to detect changes to model objects and create an execution context for expressions. There is one root scope for the application (ng-app) with hierarchical children scopes. It marshals the model to the view and forwards events to the controller.
Controller
The Controller is responsible for construction of the model and connects it to the view (HTML). The scope sits between the controller and the view. Controllers should be straightforward and simply contain the business logic needed for a view. Generally you want thin controllers and rich services. Controllers can be nested and handle inheritance. The big difference in AngularJS from the other JavaScript frameworks is there is no DOM manipulation in controllers. It is something to unlearn when developing in AngularJS.
Model
In AngularJS, a Model is simply a JavaScript object. No need to extend anything or create any structure. This allows for nested models - something that Backbone doesn’t do out-of-the-box.
View
The View is based on DOM objects, not on strings. The view is the HTML. HTML is declarative – well suited for UI design. The View should not contain any functional behavior. The flexibility here is to allow for multiple views per Controller.
Services
The Services in AngularJS are singletons that perform common tasks for web applications. If you need to share common functionality between Controllers, then use Services. Built-in AngularJS, Services start with a $. There are several ways to build a service: Service API, Factory API, or the $provide API.
Data Binding
Data Binding in AngularJS is a two-way binding between the View and the Model. Automatic synchronizing between views and data models makes this really easy (and straightforward) to use. Updating the model is reflected in View without any explicit JavaScript code to bind them together, or to add event listeners to reflect data changes.
Directives
Now this is cool. AngularJS allows you to use Directives to transform the DOM or to create new behavior. A directive allows you to extend the HTML vocabulary in a declarative fashion. The ‘ng’ prefix stands for built-in AngularJS directives. The App (ng-app), Model (ng-model), the Controller (ng-controller), etc. are built into the framework. AngularJS allows for building your own directives. Building directives is not extremely difficult, but not easy either. There are different things that can be done with them. Please check out AngularJS’s documentation on directives.
Filters
The Filters in AngularJS perform data transformation. They can be used to do formatting (like I did in my Directives example with padding zeros), or they can be used to do filter results (think search).
Validation
AngularJS has some built-in validation around HTML5 input variables (text, number, URL, email, radio, checkbox) and some directives (required, pattern, minlength, maxlength, min, max). If you want to create your own validation, it is just as simple as creating a directive to perform your validation.
Testable
Testing is a big concern for enterprise applications. There are several different ways to write and run tests against JavaScript code, thus against AngularJS. The developers at AngularJS advocate using Jasmine tests ran using Testacular. I have found this method of testing very straightforward and, while writing tests may not be the most enjoyable, it is just as importable as any other piece of developing an application.
What is a scope in AngularJS?
Ans. scope is an object that refers to the application model. It is the glue between application controller and the view. Both the controllers and directives have reference to the scope, but not with each other. It is an execution context for expressions and arranged in hierarchical structure. Scopes can watch expressions and propagate events.
Can you explain the concept of scope hierarchy? How many scopes can an application have?
Ans.
Each Angular application has exactly one root scope, but may have several child scopes. The application can have multiple scopes, because child controllers and some directives create new child scopes. When new scopes are created, they are added as children of their parent scope. This creates a hierarchical structure similar to the DOM where they're attached.
When Angular evaluates a bound variable like say {{firstName}}, it first looks at the scope associated with the given element for the firstName property. If no such property is found, it searches the parent scope and so on until the root scope is reached. In JavaScript this behaviour is known as prototypical inheritance, and child scopes prototypically inherit from their parents. The reverse is not true. i.e. the parent can't see it's children's bound propertie
Is AngularJS a templating system?
Ans. At the highest level, Angular does look like a just another templating system. But there is one important reason why the Angular templating system is different, that makes it very good fit for application development: bidirectional data binding. The template is compiled in the browser and the compilation step produces a live view. This means you, the developers, don't need to write code to constantly sync the view with the model and the model with the view as in other templating systems.Do I need to worry about security holes in AngularJS?
Ans.
Like any other technology, AngularJS is not impervious to attack. Angular does, however, provide built-in protection from basic security holes including cross-site scripting and HTML injection attacks. AngularJS does round-trip escaping on all strings for you and even offers XSRF protection for server-side communication.
AngularJS was designed to be compatible with other security measures like Content Security Policy (CSP), HTTPS (SSL/TLS) and server-side authentication and authorization that greatly reduce the possible attack vectors and we highly recommended their use.
What are the key differences between AngularJS and jQuery?
Ans.
AngularJS and jQuery are the Javascript frameworks and are different with each other, so never mix up the AngularJS and jQuery code in your project. Use only one Javascript framework at a time. If you are starting a new project, must consider AngularJS over jQuery. If you are a experienced jQuery developer, then you have to invest some time to work in AngularJS way. There are a lot of difference between AngularJS and jQuery.
1. Web designing approach in jQuery and AngularJS
In jQuery, you design a page, and then you make it dynamic. This is because jQuery was designed for augmentation and has grown incredibly from that simple premise.
But in AngularJS, you must start from the ground up with your architecture in mind. Instead of starting by thinking "I have this piece of the DOM and I want to make it do X", you have to start with what you want to accomplish, then go about designing your application, and then finally go about designing your view.
2. Don't augment jQuery with AngularJS
Similarly, don't start with the idea that jQuery does X, Y, and Z, so I'll just add AngularJS on top of that for models and controllers. This is really tempting when you're just starting out, which is why I always recommend that new AngularJS developers don't use jQuery at all, at least until they get used to doing things the "Angular Way".
I've seen many developers here and on the mailing list create these elaborate solutions with jQuery plugins of 150 or 200 lines of code that they then glue into AngularJS with a collection of callbacks and $applys that are confusing and convoluted; but they eventually get it working! The problem is that in most cases that jQuery plugin could be rewritten in AngularJS in a fraction of the code, where suddenly everything becomes comprehensible and straightforward.
The bottom line is this: when solutioning, first "think in AngularJS"; if you can't think of a solution, ask the community; if after all of that there is no easy solution, then feel free to reach for the jQuery. But don't let jQuery become a crutch or you'll never master AngularJS.
3. Always think in terms of architecture
First know that single-page applications are applications. They're not webpages. So we need to think like a server-side developer in addition to thinking like a client-side developer. We have to think about how to divide our application into individual, extensible, testable components.
So then how do you do that? How do you "think in AngularJS"? Here are some general principles, contrasted with jQuery.
The view is the "official record"
In jQuery, we programmatically change the view. We could have a dropdown menu defined as a ul like so:
<ul class="main-menu">
<li class="active">
<a href="#/home">Home</a>
</li>
<li>
<a href="#/menu1">Menu 1</a>
<ul>
<li><a href="#/sm1">Submenu 1</a></li>
<li><a href="#/sm2">Submenu 2</a></li>
<li><a href="#/sm3">Submenu 3</a></li>
</ul>
</li>
<li>
<a href="#/home">Menu 2</a>
</li>
</ul>
In jQuery, in our application logic, we would activate it with something like:
$('.main-menu').dropdownMenu();
When we just look at the view, it's not immediately obvious that there is any functionality here. For small applications, that's fine. But for non-trivial applications, things quickly get confusing and hard to maintain.
In AngularJS, though, the view is the official record of view-based functionality. Our ul declaration would look like this instead:
<ul class="main-menu" dropdown-menu>
...
</ul>
These two do the same thing, but in the AngularJS version anyone looking at the template knows what's supposed to happen. Whenever a new member of the development team comes on board, he can look at this and then know that there is a directive called dropdownMenu operating on it; he doesn't need to intuit the right answer or sift through any code. The view told us what was supposed to happen. Much cleaner.
Developers new to AngularJS often ask a question like: how do I find all links of a specific kind and add a directive onto them. The developer is always flabbergasted when we reply: you don't. But the reason you don't do that is that this is like half-jQuery, half-AngularJS, and no good. The problem here is that the developer is trying to "do jQuery" in the context of AngularJS. That's never going to work well. The view is the official record. Outside of a directive (more on this below), you never, ever, never change the DOM. And directives are applied in the view, so intent is clear.
Remember: don't design, and then mark up. You must architect, and then design.
Data binding
This is by far one of the most awesome features of AngularJS and cuts out a lot of the need to do the kinds of DOM manipulations I mentioned in the previous section. AngularJS will automatically update your view so you don't have to! In jQuery, we respond to events and then update content. Something like:
$.ajax({
url: '/myEndpoint.json',
success: function ( data, status ) {
$('ul#log').append('<li>Data Received!</li>');
}
});
For a view that looks like this:
<ul class="messages" id="log">
</ul>
Apart from mixing concerns, we also have the same problems of signifying intent that I mentioned before. But more importantly, we had to manually reference and update a DOM node. And if we want to delete a log entry, we have to code against the DOM for that too. How do we test the logic apart from the DOM? And what if we want to change the presentation?
This a little messy and a trifle frail. But in AngularJS, we can do this:
$http( '/myEndpoint.json' ).then( function ( response ) {
$scope.log.push( { msg: 'Data Received!' } );
});
And our view can look like this:
<ul class="messages">
<li ng-repeat="entry in log">{{ entry.msg }}</li>
</ul>
But for that matter, our view could look like this:
<div class="messages">
<div class="alert" ng-repeat="entry in log">
{{ entry.msg }}
</div>
</div>
And now instead of using an unordered list, we're using Bootstrap alert boxes. And we never had to change the controller code! But more importantly, no matter where or how the log gets updated, the view will change too. Automatically. Neat!
Though I didn't show it here, the data binding is two-way. So those log messages could also be editable in the view just by doing this:
<input ng-model="entry.msg" />.
And there was much rejoicing.
Distinct model layer
In jQuery, the DOM is kind of like the model. But in AngularJS, we have a separate model layer that we can manage in any way we want, completely independently from the view. This helps for the above data binding, maintains separation of concerns, and introduces far greater testability. Other answers mentioned this point, so I'll just leave it at that.
Separation of concerns
And all of the above tie into this over-arching theme: keep your concerns separate. Your view acts as the official record of what is supposed to happen (for the most part); your model represents your data; you have a service layer to perform reusable tasks; you do DOM manipulation and augment your view with directives; and you glue it all together with controllers. This was also mentioned in other answers, and the only thing I would add pertains to testability, which I discuss in another section below.
Dependency injection
To help us out with separation of concerns is dependency injection (DI). If you come from a server-side language (from Java to PHP) you're probably familiar with this concept already, but if you're a client-side guy coming from jQuery, this concept can seem anything from silly to superfluous to hipster. But it's not.
From a broad perspective, DI means that you can declare components very freely and then from any other component, just ask for an instance of it and it will be granted. You don't have to know about loading order, or file locations, or anything like that. The power may not immediately be visible, but I'll provide just one (common) example: testing.
Let's say in our application, we require a service that implements server-side storage through a REST API and, depending on application state, local storage as well. When running tests on our controllers, we don't want to have to communicate with the server - we're testing the controller, after all. We can just add a mock service of the same name as our original component, and the injector will ensure that our controller gets the fake one automatically - our controller doesn't and needn't know the difference.
4. Test-driven development
This is really part of section 3 on architecture, but it's so important that I'm putting it as its own top-level section.
Out of all of the many jQuery plugins you've seen, used, or written, how many of them had an accompanying test suite? Not very many because jQuery isn't very amenable to that. But AngularJS is.
In jQuery, the only way to test is often to create the component independently with a sample/demo page against which our tests can perform DOM manipulation. So then we have to develop a component separately and then integrate it into our application. How inconvenient! So much of the time, when developing with jQuery, we opt for iterative instead of test-driven development. And who could blame us?
But because we have separation of concerns, we can do test-driven development iteratively in AngularJS! For example, let's say we want a super-simple directive to indicate in our menu what our current route is. We can declare what we want in our view:
<a href="/hello" when-active>Hello</a>
Okay, now we can write a test:
it( 'should add "active" when the route changes', inject(function() {
var elm = $compile( '<a href="/hello" when-active>Hello</a>' )( $scope );
$location.path('/not-matching');
expect( elm.hasClass('active') ).toBeFalsey();
$location.path( '/hello' );
expect( elm.hasClass('active') ).toBeTruthy();
}));
We run our test and confirm that it fails. So now we can write our directive:
.directive( 'whenActive', function ( $location ) {
return {
scope: true,
link: function ( scope, element, attrs ) {
scope.$on( '$routeChangeSuccess', function () {
if ( $location.path() == element.attr( 'href' ) ) {
element.addClass( 'active' );
}
else {
element.removeClass( 'active' );
}
});
}
};
});
Our test now passes and our menu performs as requested. Our development is both iterative and test-driven.
5. Conceptually, directives are not packaged jQuery
You'll often hear "only do DOM manipulation in a directive". This is a necessity. Treat it with due deference!
But let's dive a little deeper...
Some directives just decorate what's already in the view (think ngClass) and therefore sometimes do DOM manipulation straight away and then are basically done. But if a directive is like a "widget" and has a template, it should also respect separation of concerns. That is, the template too should remain largely independent from its implementation in the link and controller functions.
AngularJS comes with an entire set of tools to make this very easy; with ngClass we can dynamically update the class; ngBind allows two-way data binding; ngShow and ngHide programmatically show or hide an element; and many more - including the ones we write ourselves. In other words, we can do all kinds of awesomeness without DOM manipulation. The less DOM manipulation, the easier directives are to test, the easier they are to style, the easier they are to change in the future, and the more re-usable and distributable they are.
I see lots of developers new to AngularJS using directives as the place to throw a bunch of jQuery. In other words, they think "since I can't do DOM manipulation in the controller, I'll take that code put it in a directive". While that certainly is much better, it's often still wrong.
Think of the logger we programmed in section 3. Even if we put that in a directive, we still want to do it the "Angular Way". It still doesn't take any DOM manipulation! There are lots of times when DOM manipulation is necessary, but it's a lot rarer than you think! Before doing DOM manipulation anywhere in your application, ask yourself if you really need to. There might be a better way.
Here's a quick example that shows the pattern I see most frequently. We want a toggleable button. (Note: this example is a little contrived and a skosh verbose to represent more complicated cases that are solved in exactly the same way.)
.directive( 'myDirective', function () {
return {
template: '<a class="btn">Toggle me!</a>',
link: function ( scope, element, attrs ) {
var on = false;
$(element).click( function () {
if ( on ) {
$(element).removeClass( 'active' );
}
else {
$(element).addClass( 'active' );
}
on = !on;
});
}
};
});
There are a few things wrong with this. First, jQuery was never necessary. There's nothing we did here that needed jQuery at all! Second, even if we already have jQuery on our page, there's no reason to use it here; we can simply use angular.element and our component will still work when dropped into a project that doesn't have jQuery. Third, even assuming jQuery was required for this directive to work, jqLite (angular.element) will always use jQuery if it was loaded! So we needn't use the $ - we can just use angular.element. Fourth, closely related to the third, is that jqLite elements needn't be wrapped in $ - the element that is passed to the link function would already be a jQuery element! And fifth, which we've mentioned in previous sections, why are we mixing template stuff into our logic?
This directive can be rewritten (even for very complicated cases!) much more simply like so:
.directive( 'myDirective', function () {
return {
scope: true,
template: '<a class="btn" ng-class="{active: on}" ng-click="toggle()">Toggle me!</a>',
link: function ( scope, element, attrs ) {
scope.on = false;
scope.toggle = function () {
scope.on = !scope.on;
};
}
};
});
Again, the template stuff is in the template, so you (or your users) can easily swap it out for one that meets any style necessary, and the logic never had to be touched.
And there are still all those other benefits, like testing - it's easy! No matter what's in the template, the directive's internal API is never touched, so refactoring is easy. You can change the template as much as you want without touching the directive. And no matter what you change, your tests still pass.
So if directives aren't just collections of jQuery-like functions, what are they? Directives are actually extensions of HTML. If HTML doesn't do something you need it to do, you write a directive to do it for you, and then use it just as if it was part of HTML.
Put another way, if AngularJS doesn't do something out of the box, think how the team would accomplish it to fit right in with ngClick, ngClass, et al.
How will you display different images based on the status being red, amber, or green?
Ans.
Use the ng-switch and ng-switch-when directives as shown below.
<div ng-switch on="account.status">
<div ng-switch-when="AMBER">
<img class="statusIcon"
src='apps/dashboard/amber-dot.jpg' />
</div>
<div ng-switch-when="GREEN">
<img class="statusIcon"
src='apps/dashboard/green-dot.jpg' />
</div>
<div ng-switch-when="RED">
<img class="statusIcon"
src='apps/dashboard/red-dot.jpg' />
</div>
</div>
How will you initialize a select box with options on page load?
Ans.
Use the ng-init directive.
<div ng-controller="apps/dashboard/account" ng-switch
on="!!accounts" ng-init="loadData()">
How will you show/hide buttons and enable/disable buttons conditionally?
Ans.
Using the ng-show and ng-disabled directives.
<div class="dataControlPanel"
ng-show="accounts.releasePortfolios">
<div class="dataControlButtons">
<button class="btn btn-primary btn-small"
ng-click="saveComments()" ng-disabled="disableSaveButton">Save</button>
<button class="btn btn-primary btn-small"
ng-click="releaseRun()" ng-disabled="disableReleaseButton">Release</button>
</div>
</div>
How will you loop through a collection and list each item?
Ans.
Using the ng-repeat directive.
<table
class="table table-bordered table-striped table-hover table-fixed-head portal-data-table">
<thead>
<tr>
<th>account</th>
<th>Difference</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr
ng-repeat="account in acounts">
<td width="40%">{{account.accountCode}}</td>
<td width="30%" style="text-align: right">{{account.difference
| currency: ""}}</td>
<td width="30%">
<div ng-switch on="account.status">
<div ng-switch-when="AMBER">
<img class="statusIcon"
src='apps/dashboard/amber-dot.jpg' />
</div>
<div ng-switch-when="GREEN">
<img class="statusIcon"
src='apps/dashboard/green-dot.jpg' />
</div>
<div ng-switch-when="RED">
<img class="statusIcon"
src='apps/dashboard/red-dot.jpg' />
</div>
</div>
</td>
</tr>
</tbody>
</table>
How will you add options to a select box?
Ans.
Using the ng-options and ng-model directives.
<fieldset>
<dl class="control-group">
<dt>
<label for="cientId">
<h4>Client Id:</h4>
</label>
</dt>
<dd>
<select id="cientId" class="input-xlarge" ng-model="clientId"
ng-options="reportClient.clientId as reportClient.clientId for reportClient in reportClients "
ng-click="getReportParams()" ng-change="getValuationDates()" />
</dd>
</dl>
<dl class="control-group">
<dt>
<label for="valuationDate">
<h4>
Valuation Date <small>(dd/mm/yyyy)</small>
</h4>
</label>
</dt>
<dd>
<select id="valuationDate" class="input-xlarge"
ng-model="valuationDate"
ng-options="reportdate for reportdate in reportDates" />
</dd>
</dl>
</fieldset>
How will you display inprogress revolving image to indicate that RESTful data is bing loaded?
Ans.
<div ng-show="loading">
<img class="loading" src="portal/images/loading_32.gif" />
</div>
$scope.loadReportData = function($http) {
$scope.loading = true; // start spinng the image
$http(
{
method : 'GET',
url : propertiesService.get('restPath')
+ '/myapp/portfolio/'
+ $scope.clientId
+ '/'
+ dateService
.userToRest($scope.reportDate),
cacheBreaker : true
}).success(
function(data, config) {
$scope.reportData = data;
portal.log('reportData: ',
$scope.reportData);
$scope.loading = false; // stop spinning the image
}).error(
function(data, status, headers, config) {
if(data.errorMsg != null) {
$scope.httpError = data.errorMsg;
}
else {
$scope.httpError = "Error retrieving data from " + errorService
.getApacheErrorTitleMessage(status,
data, config);
}
$scope.loading = false; // stop spinning the image
});
};
===============
What are the ways to communicate between modules of your application using core AngularJS functionality? Name three ways.
Communication can happen:
- Using services
- Using events
- By assigning models on $rootScope
- Directly between controllers, using $parent, nextSibling, etc
- Directly between controllers, using ControllerAs, or other forms of inheritence
In the community, there are also mentions of less popular methods such as using watches or the URL.
Which means of communication between modules of your application are easily testable?
Using a service is definitely easy to test. Services are injected, and in a test either a real service can be used or it can be mocked.
Events can be tested. In unit testing controllers, they usually are instantiated. For testing events on $rootScope, it must be injected into the test.
Testing $rootScope against the existence of some arbitrary models is testable, but sharing data through $rootScope is not considered a good practice.
For testing direct communication between controllers, the expected results should probably be mocked. Otherwise, controllers would need to be manually instantiated to have the right context.
The most popular e2e testing tool for AngularJS is Protractor. There are also others which rely on similar mechanisms. Describe how e2e testing of AngularJS applications work.
The e2e tests are executed against a running app, that is a fully initialized system. They most often spawn a browser instance and involve the actual input of commands through the user interface. The written code is evaluated by an automation program, such as a Selenium server (webdriver). That program sends commands to a browser instance, then evaluates the visible results and reports back to the user.
The assertions are handled by another library, for Protractor the default is Jasmine. Before Protractor, there was a module called Angular Scenarios, which usually was executed through Karma, and is now deprecated. Should you want to e2e test hybrid apps, you could use another Selenium server, called Appium.
Testing can be handled manually, or it can be delegated to continuous integration servers, either custom or ones provided by Travis, SauceLabs, and Codeship.
This is a simple test written for Protractor, a slightly modified example from Protractor docs:
it('should find an element by text input model', function() {
browser.get('/some-url');
var login = element(by.model('username'));
login.clear();
login.sendKeys('Jane Doe');
var name = element(by.binding('username'));
expect(name.getText()).toEqual('Jane Doe');
// Point A
});
Explain if the code is synchronous or asynchronous and how it works.
The code is asynchronous, although it is written in a synchronous manner. What happens under the hood is that all those functions return promises on the control flow. There is even direct access, using “protractor.promise.controlFlow()”, and the two methods of the returned object, “.execute()” and “.await()”.
Other webdriver libraries, such as wd https://github.com/admc/wd, require the direct use of callbacks or promise chains.
When a scope is terminated, two similar “destroy” events are fired. What are they used for, and why are there two?
The first one is an AngularJS event, “$destroy”, and the second one is a jqLite / jQuery event “$destroy”. The first one can be used by AngularJS scopes where they are accessible, such as in controllers or link functions.
Consider the two below happening in a directive’s postLink function. The AngularJS event:
scope.$on(‘$destroy’, function () {
// handle the destroy, i.e. clean up.
});
And
element.on(‘$destroy’, function () {
// respectful jQuery plugins already have this handler.
// angular.element(document.body).off(‘someCustomEvent’);
});
The jqLite / jQuery event is called whenever a node is removed, which may just happen without scope teardown.
How do you reset a “$timeout”, and disable a “$watch()”?
The key to both is assigning the result of the function to a variable.
To cleanup the timeout, just “.cancel()” it:
var customTimeout = $timeout(function () {
// arbitrary code
}, 55);
$timeout.cancel(customTimeout);
The same applies to “$interval()”.
To disable a watch, just call it.
// .$watch() returns a deregistration function that we store to a variable
var deregisterWatchFn = $rootScope.$watch(‘someGloballyAvailableProperty’, function (newVal) {
if (newVal) {
// we invoke that deregistration function, to disable the watch
deregisterWatchFn();
...
}
});
Name and describe the phases of a directive definition function execution, or describe how directives are instantiated.
The flow is as follows:
First, the “$compile()” function is executed which returns two link functions, preLink and postLink. That function is executed for every directive, starting from parent, then child, then grandchild.
Secondly, two functions are executed for every directive: the controller and the prelink function. The order of execution again starts with the parent element, then child, then grandchild, etc.
The last function postLink is executed in the inverse order. That is, it is first executed for grandchild, then child, then parent.
A great explanation of how directives are handled in AngularJS is available in the AngularJS Tutorial: Demystifying Custom Directives post on the Toptal blog.
How does interpolation, e.g. “{{ someModel }}”, actually work?
It relies on $interpolation, a service which is called by the compiler. It evaluates text and markup which may contain AngularJS expressions. For every interpolated expression, a “watch()” is set. $interpolation returns a function, which has a single argument, “context”. By calling that function and providing a scope as context, the expressions are “$parse()”d against that scope.How does the digest phase work?
In a nutshell, on every digest cycle all scope models are compared against their previous values. That is dirty checking. If change is detected, the watches set on that model are fired. Then another digest cycle executes, and so on until all models are stable.
It is probably important to mention that there is no “.$digest()” polling. That means that every time it is being called deliberately. As long as core directives are used, we don’t need to worry, but when external code changes models the digest cycle needs to be called manually. Usually to do that, “.$apply()” or similar is used, and not “.$digest()” directly.
List a few ways to improve performance in an AngularJS app.
The two officially recommended methods for production are disabling debug data and enabling strict DI mode.
The first one can be enabled through the $compileProvider:
myApp.config(function ($compileProvider) {
$compileProvider.debugInfoEnabled(false);
});
That tweak disables appending scope to elements, making scopes inaccessible from the console. The second one can be set as a directive:
<html ng-app=“myApp” ng-strict-di>
The performance gain lies in the fact that the injected modules are annotated explicitly, hence they don’t need to be discovered dynamically.
You don’t need to annotate yourself, just use some automated build tool and library for that.
Two other popular ways are:
- Using one-time binding where possible. Those bindings are set, e.g. in “{{ ::someModel }}” interpolations by prefixing the model with two colons. In such a case, no watch is set and the model is ignored during digest.
- Making $httpProvider use applyAsync:
myApp.config(function ($httpProvider) {
$httpProvider.useApplyAsync(true);
});
… which executes nearby digest calls just once, using a zero timeout.
===============
===============
References : -
http://www.codeproject.com/Articles/891718/AngularJS-Interview-Questions-and-Answers
http://career.guru99.com/top-25-angular-js-interview-questions/
http://www.withoutbook.com/Technology.php?tech=63&page=5&subject=Angular%20JS%20Interview%20Questions%20and%20Answers
What re scopes?
Scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events.AngularJS and scope.$apply
If you’ve written a non-trivial amount of code in AngularJS, you may have come across the
$scope.$apply() method. On the surface, it may seem like just a method you call to get your bindings to update. But why does it exist? And when do you need to use it?
To really understand when to use
$apply, it’s good to know exactly why we need to use it, so let’s dive in!JavaScript is Turn Based
The JavaScript code we write doesn’t all run in one go, instead it executes in turns. Each of these turns runs uninterupted from start to finish, and when a turn is running, nothing else happens in our browser. No other JavaScript code runs, and our web page interface is completely frozen. This is why poorly coded JavaScript can freeze a web page.
Instead, whenever there is a task that takes some amount of time, such as an Ajax request, waiting for a click event, or setting a timeout, we set up a callback function and finish our current turn. Later, when the Ajax request completes, a click is detected, or the timer completes, a new JavaScript turn is created and the callback is run to completion.
Let’s look at an example JavaScript file:
var button = document.getElementById('clickMe');
function buttonClicked () {
alert('the button was clicked');
}
button.addEventListener('click', buttonClicked);
function timerComplete () {
alert('timer complete');
}
setTimeout(timerComplete, 2000);
When the JavaScript code is loaded, that is a single turn. It finds a button, adds a click listener, and sets a timeout. Then the turn is complete, and the browser will update the web page if necessary, and begin accepting user input.
If the browser detects a click on
#clickMe, it creates a new turn, which executes thebuttonClicked function. When that function returns, that turn is complete.
After 2000 milliseconds, the browser creates a new turn which calls
timerComplete.
Our JavaScript code is run in turns, and in between the turns is when the page is repainted, and input is accepted.
How do we update bindings?
So Angular lets us bind parts of our interface to data in our JavaScript code, but how does it know when data changes, and the page needs updating?
There are a few solutions. The code needs to know when a value has changed. Right now there is no way for our code to be directly notified of changes on an object 1. Instead there are two main strategies.
One strategy is to use special objects, where data is set via methods, not property assignments. Then changes can then be noted, and the page can be updated. This has the downside in that we must extend some special object. Also, for assigning, we must use a more verbose form
obj.set('key', 'value') instead of obj.key = 'value'. Frameworks like EmberJS and KnockoutJS use this strategy.
AngularJS takes a different approach: allow any value to be used as a binding target. Then at the end of any JavaScript code turn, check to see if the value has changed. This may seem inneficient at first, but there are some clever strategies to reduce the performance hit. The big benefit is we can use normal objects and update our data however we want, and the changes will be noticed and reflected in our bindings.
For this strategy to work, we need to know when data has possibly changed, and this is where
$scope.$apply comes into play.$apply and $digest
That step that checks to see if any binding values have changed actually has a method,
$scope.$digest(). That’s actually where the magic happens, but we almost never call it directly, instead we use $scope.$apply() which will call $scope.$digest() for you.$scope.$apply() takes a function or an Angular expression string, and executes it, then calls $scope.$digest() to update any bindings or watchers.
So, when do you need to call
$apply()? Very rarely, actually. AngularJS actually calls almost all of your code within an $apply call. Events like ng-click, controller initialization, $http callbacks are all wrapped in $scope.$apply(). So you don’t need to call it yourself, in fact you can’t. Calling $apply inside $apply will throw an error.
You do need to use it if you are going to run code in a new turn. And only if that turn isn’t being created from a method in the AngularJS library. Inside that new turn, you should wrap your code in
$scope.$apply(). Here is an example. We are using setTimeout, which will execute a function in a new turn after a delay. Since Angular doesn’t know about that new turn, the update will not be reflected.
But, if we wrap the code for that turn in
$scope.$apply(), the change will be noticed, and the page is updated.
As a convenience, AngularJS provides $timeout, which is like
setTimeout, but automatically wraps your code in $apply by default. Use that, not this
If you write any code that uses Ajax without
$http, or listens for events without using Angular’s ng-* listeners, or sets a timeout without $timeout, you should wrap your code in $scope.$apply$scope.$apply() vs $scope.$apply(fn)
Sometimes I see examples where data is updated, and then
$scope.$apply() is called with no arguments. This achieves the desired result, but misses some opportunities.
If your code isn’t wrapped in a function passed to $apply, and it throws an error, that error is thrown outside of AngularJS, which means any error handling being used in your application is going to miss it. $apply not only runs your code, but it runs it in a
try/catch so your error is always caught, and the $digest call is in a finally clause, meaning it will run regardless of an error being thrown. That’s pretty nice.
Hopefully now you understand what
$apply is and when to use it. If you only use what AngularJS provides you, you shouldn’t need to use it often. But if you begin writing directives where you are observing DOM elements directly, it is going to become necessary.
===================================================
AngularJs Material JS and CSS for various css and js effects
Reference:
https://material.angularjs.org/latest
=========================================================================
REST (representational state transfer) API -
REST (REpresentational State Transfer) is an architectural style, and an approach to communications that is often used in the development of Web services. The use of REST is often preferred over the more heavyweight SOAP (Simple Object Access Protocol) style because REST does not leverage as much bandwidth, which makes it a better fit for use over the Internet. The SOAP approach requires writing or using a provided server program (to serve data) and a client program (to request data).How to Architect a Modern Distributed SOA
SOA based principles shouldn't be thought of as being mysterious, hard to learn, or magical. Gain expert advice on how to effectively build a distributed enterprise architecture from requirements to resources.
REST'S decoupled architecture, and lighter weight communications between producer and consumer, make REST a popular building style for cloud-based APIs, such as those provided by Amazon, Microsoft, and Google. When Web services use REST architecture, they are called RESTful APIs (Application Programming Interfaces) or REST APIs.
REST architecture involves reading a designated Web page that contains an XML file. The XML file describes and includes the desired content. Once dynamically defined, consumers may access the interface.
REST, which typically runs over HTTP (Hypertext Transfer Protocol), has several architectural constraints:
1. Decouples consumers from producers
2. Stateless existence
3. Able to leverage a cache
4. Leverages a layered system
5. Leverages a uniform interface
REST is often used in mobile applications, social networking Web sites, mashup tools, and automated business processes. The REST style emphasizes that interactions between clients and services is enhanced by having a limited number of operations (verbs). Flexibility is provided by assigning resources (nouns) their own unique Universal Resource Identifiers (URIs). Because each verb has a specific meaning (GET, POST, PUT and DELETE), REST avoids ambiguity.
There are some downsides. In the world of REST, there is no direct support for generating a client from server-side-generated metadata. SOAP is able to support this with Web Service Description Language (WSDL).
REST provides the following advantages, specifically advantages over leveraging SOAP:
RESTful Web services are easy to leverage by most tools, including those that are free and inexpensive. REST is becoming the dial tone for systems interaction, including the use of RESTful Web services, which are, for the most part, the way cloud providers externalize their cloud services.
SOAP services are much harder to scale than RESTful services. Thus, REST is often chosen as the architecture for services that are exposed via the Internet (like Facebook, MySpace, Twitter, and most public cloud providers).
The learning curve seems to be reduced. Developers are able to make use of REST from within applications faster than they can with SOAP. This saves time, which saves money.
REST uses a smaller message format than SOAP. SOAP uses XML for all messages, which makes the message size much larger, and thus less efficient. This means REST provides better performance, as well as lowers costs over time. Moreover, there is no intensive processing required, thus it’s much faster than traditional SOAP.
REST is designed for use over the Open Internet/Web. This is a better choice for Web scale applications, and certainly for cloud-based platforms.
Moving forward, REST is likely to continue its growth as enterprises seek to provide open and well-defined interfaces for application and infrastructure services. The growth of public and private cloud computing is driving much of this demand, and will continue to drive growth into the future.
What exactly is RESTful programming?
>>>
REST is the underlying architectural principle of the web. The amazing thing about the web is the fact that clients (browsers) and servers can interact in complex ways without the client knowing anything beforehand about the server and the resources it hosts. The key constraint is that the server and client must both agree on the media used, which in the case of the web is HTML.
An API that adheres to the principles of REST does not require the client to know anything about the structure of the API. Rather, the server needs to provide whatever information the client needs to interact with the service. An HTML form is an example of this: The server specifies the location of the resource, and the required fields. The browser doesn't know in advance where to submit the information, and it doesn't know in advance what information to submit. Both forms of information are entirely supplied by the server. (This principle is called HATEOAS.)
So, how does this apply to HTTP, and how can it be implemented in practice? HTTP is oriented around verbs and resources. The two verbs in mainstream usage are GET and POST, which I think everyone will recognize. However, the HTTP standard defines several others such as PUT and DELETE. These verbs are then applied to resources, according to the instructions provided by the server.
For example, Let's imagine that we have a user database that is managed by a web service. Our service uses a custom hypermedia based on JSON, for which we assign the mimetype application/json+userdb (There might also be an application/xml+userdb and application/whatever+userdb - many media types may be supported). The client and the server has both been programmed to understand this format, but they don't know anything about each other. As Roy Fielding points out:
A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.
A request for the base resource / might return something like this:
Request
GET /
Accept: application/json+userdb
Response
200 OK
Content-Type: application/json+userdb
{
"version": "1.0",
"links": [
{
"href": "/user",
"rel": "list",
"method": "GET"
},
{
"href": "/user",
"rel": "create",
"method": "POST"
}
]
}
We know from the description of our media that we can find information about related resources from sections called "links". This is called Hypermedia controls. In this case, we can tell from such a section that we can find a user list by making another request for /user:
Request
GET /user
Accept: application/json+userdb
Response
200 OK
Content-Type: application/json+userdb
{
"users": [
{
"id": 1,
"name": "Emil",
"country: "Sweden",
"links": [
{
"href": "/user/1",
"rel": "self",
"method": "GET"
},
{
"href": "/user/1",
"rel": "edit",
"method": "PUT"
},
{
"href": "/user/1",
"rel": "delete",
"method": "DELETE"
}
]
},
{
"id": 2,
"name": "Adam",
"country: "Scotland",
"links": [
{
"href": "/user/2",
"rel": "self",
"method": "GET"
},
{
"href": "/user/2",
"rel": "edit",
"method": "PUT"
},
{
"href": "/user/2",
"rel": "delete",
"method": "DELETE"
}
]
}
],
"links": [
{
"href": "/user",
"rel": "create",
"method": "POST"
}
]
}
We can tell a lot from this response. For instance, we now know we can create a new user by POSTing to /user:
Request
POST /user
Accept: application/json+userdb
Content-Type: application/json+userdb
{
"name": "Karl",
"country": "Austria"
}
Response
201 Created
Content-Type: application/json+userdb
{
"user": {
"id": 3,
"name": "Karl",
"country": "Austria",
"links": [
{
"href": "/user/3",
"rel": "self",
"method": "GET"
},
{
"href": "/user/3",
"rel": "edit",
"method": "PUT"
},
{
"href": "/user/3",
"rel": "delete",
"method": "DELETE"
}
]
},
"links": {
"href": "/user",
"rel": "list",
"method": "GET"
}
}
We also know that we can change existing data:
Request
PUT /user/1
Accept: application/json+userdb
Content-Type: application/json+userdb
{
"name": "Emil",
"country": "Bhutan"
}
Response
200 OK
Content-Type: application/json+userdb
{
"user": {
"id": 1,
"name": "Emil",
"country": "Bhutan",
"links": [
{
"href": "/user/1",
"rel": "self",
"method": "GET"
},
{
"href": "/user/1",
"rel": "edit",
"method": "PUT"
},
{
"href": "/user/1",
"rel": "delete",
"method": "DELETE"
}
]
},
"links": {
"href": "/user",
"rel": "list",
"method": "GET"
}
}
Notice that we are using different HTTP verbs (GET, PUT, POST, DELETE etc.) to manipulate these resources, and that the only knowledge we presume on the clients part is our media definition.

Today's Best article. It really helps me to enhance my skills.
ReplyDeleteAWS Training in Chennai
DevOps Training in Chennai
Java Training in Chennai
AngularJS Training in Chennai
AngularJS Training
Nice articel, This article help me very well. Thank you. Also please check my article on my site about What Is Angular?.
ReplyDelete