Sie sind auf Seite 1von 93

What is AngularJS and Why to use it?

AngularJS is an open-source JavaScript framework developed by Google. It helps you to create singlepage applications, one-page web applications that only require HTML, CSS, and JavaScript on the client
side. It is based on MV-* pattern and build well structured, easily testable, and maintainable front-end
applications.

AngularJS has changed the way to web development. It does not based on jQuery to perform its
operations. Till now you are using ASP.NET, ASP.NET MVC, PHP, JSP, Ruby on Rails for web
development but now you can do your complete web development by using most powerful and
adaptive JavaScript Framework AngularJS. There is no doubt, JavaScript frameworks like AngularJs,
Ember etc. are the future of web development.

How AngularJS
Framework?

is

different

from

other

JavaScript

1. AngularJS markup lives in the DOM.


2. AngularJS uses plain old JavaScript objects.
3. AngularJS is leverages with Dependency Injection.
Today, AngularJS is most popular and dominant JavaScript framework for professional web
development. It is well suited for small, large and any sized web apps and web application. This graph
of Google Search Trends shows the interest of developers into JavaScript frameworks over time:

Why Angular JS?


1.
2.
3.
4.

5.

There are numerous of reasons to choose AngularJS as you web development framework. Some of
them are listed below:
It is based on MVC pattern which helps you to properly organize your web apps or web application.
It extends HTML by attaching directives to your HTML markup with new attributes or tags and
expressions in order to define very powerful templates.
It also allows you to create your own directives, crafting reusable components that fill your needs and
abstracting away all the DOM manipulation logic.
It supports two-way data binding i.e. connects your HTML (views) to your JavaScript objects (models)
seamlessly. In this way your model will be immediately reflected into your view without the need for
any DOM manipulation or event handling (with jQuery).
It encapsulates the behavior of your application in controllers which are instantiated with the help of
dependency injection.

6. It supports services that can be injected into your controllers to use some utility code to fulfill your
need. For example it provides $http service to communicate with REST service.
7. It helps you to structure and test your JavaScript code very easily.
8. Also, AngularJS is mature community to help you. It has widely support over the internet.

AngularJS Developmet IDE


1.
2.
3.
4.
5.

Here is a small list of popular IDE used for AngularJS development.


Visual Studio 2012/2013 Express or higher
Eclipse
WebStorm
Sublime Text
TextMate

Understanding Features of AngularJS


AngularJS is most powerful and adaptive JavaScript framework by the web developers and designers.
In this article, you will learn the most important features of AngularJS and how they can help you to
make your app awesome.

AngularJS Features
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.

Modules
Directives
Templates
Scope
Expressions
DataBinding
MVC (Model, View & Controller)
Validations
Filters
Services
Routing
Dependency Injection
Testing

Modules
AngularJS modules divides your web application into small, reusable and functional components which
can be integrated with other web applications. Each module is identified by a unique name and can
be dependent on other modules.

Creating an AngularJS module


1.
2.
3.
4.

<script type="text/javascript">
angular.module('myApp',[]);
angular.module('myApp',['dependentModule1','dependentModule2']);
</script>

Using an AngularJS module into your app


You can bootstraps your app by using your angularJS module as given below:
1. <html ng-app="myApp">
2. <head>...</head>
3. <body>...</body>

1.
2.
3.
4.
5.

Inside your angularjs module you can define following components:


Controllers
Services
Factories
Filters
Directives etc.

Directives
AngularJS directives are used to extend the HTML vocabulary i.e they decorate html elements with
new behaviors and help to manipulate html elements attributes in interesting way.
There are some built-in directives provided by angularjs like as ng-app, ng-controller, ng-repeat, ngmodel etc. You can also create your own custom directive.

Using ng-repeat in Template


1. <!-- ng-repeat directive -->
2. <ul ng-controller='ProductController'>
3. <li ng-repeat='product in Products'> = </li>
4. </ul>
5.
6. <script>
7. function ProductController($scope){
8. $scope.Products = [{name: 'Soap', price: 120},
9. {name: 'Shampoo', price: 100},
10. {name: 'Hair Oil', price: 60}];
11. }
12. </script>

Templates

1.
2.
3.
4.

AngularJS templates are just plain old HTML that contains Angular-specific elements and attributes.
AngularJS used these templates to show information from the model and controller.
Inside your angularjs templates you can define following angular elements and attributes:
Directive
Angular Markup ()
Filters
Form controls

Creating Template
1. <html ng-app>
2. <!-- Body tag with ngController directive -->
3. <body ng-controller="MyController">
4. <input ng-model="foo" value="bar">
5. <!-- Button tag with ng-click directive, and string expression 'buttonText' i
s wrapped in "" markup -->
6. <button ng-click="changeFoo()"></button>
7. <script src="angular.js">
8. </body>
9. </html>

Expressions

1.
2.
3.
4.

5.
6.

Angular expressions are JavaScript-like code snippets that are usually placed in bindings such as .
AngularJS expressions doesn't support control flow statements(conditionals, loops, or exceptions).
These supports filters to format data before displaying it.
There are some valid angularjs expressions:
3
2
false
2

Data Binding
AngularJS data-binding is the most useful feature which save you from writing a considerable amount
of boilerplate code. Now, developers are not responsible for manually manipulating the DOM elements
and attributes to reflect model changes. AngularJS provides two-way data-binding to handle the
synchronization of data between model and view.
The data-binding directives helps you to bind your model data to your app view. Use ng-model
directive to create a two way data-binding between the input element and the target model.
1. <div ng-controller='HelloController'>
2. <input ng-model='name'/><!-- two way -->
3. <p>Hello </p> <!-- one way -->

4. </div>
5.
6. <script>
7. function HelloController($scope)
8. {
9. $scope.name = 'Dot Net Tricks'
10. }
11. </script>

Scope
Scope is an object that refers to the application model. It acts as a context for evaluating expressions.
Typically, it acts as a glue between controller and view. Scopes are hierarchical in nature and follow the
DOM structure of your angularjs app.
Each angular app has a single scope ($rootscope) which mapped to the ng-app directive element.

Creating $scope in controllers


1.
2.
3.
4.
5.
6.
7.
8.

<script>
function ProductController($scope){
$scope.Products = [{name: 'Soap', price: 120},
{name: 'Shampoo', price: 100},
{name: 'Hair Oil', price: 60}];
}
</script>

Using Scope in Template


1.
2.
3.
4.
5.

<!-- ng-repeat directive -->


<ul ng-controller='ProductController'>
<li ng-repeat='product in Products'> =
</li>
</ul>

MVC (Model, View & Controller)


AbgularJS is a MVC framework. It does not implement MVC in the traditional way, but rather something
closer to MVVM Model-View-ViewModel).

The Model
Models are plain old JavaScript objects that represent data used by your app. Models are also used to
represent your app's current state.

The ViewModel

A viewmodel is an object that provides specific data and methods to maintain specific views. Basically,
it is a $scope object which lives within your angularjs app's controller. A viewmodel is associated with
a HTML element with the ng-model & ng-bind directives.

Creating an AngularJS Controller with ViewModel


1. <script type="text/javascript">
2. //defining main controller
3. app.controller('mainController', ['$scope', function($scope) {
4.
5. //defining book viewmodel
6. $scope.book =
7. {
8. id: 1,
9. name: 'AngularJS Interview Questions and Answers',
10. author: 'Shailendra Chauhan',
11. };
12. }]);
13. </script>

The Controller
The controller define the actual behavior of your app. It contains business logic for the view and
connects the right models to the right views. A controller is associated with a HTML element with
the ng-controller directive.

The View
The view is responsible for presenting your models data to end user. Typically it is the HTML markup
which exists after AngularJS has parsed and compiled the HTML to include rendered markup and
bindings.

Using an AngularJS controller into your app


1. <!-- The View -->
2. <div ng-controller="mainController">
3. Id: <span ng-bind="book.id"></span>
4. <br/>
5. Name:<input type="text" ng-model="book.name" />
6. <br/>
7. Author: <input type="text" ng-model="book.author" />
8. </div>

Validation
AngularJS form validation enables you to develop a modern HTML5 form that is interactive and
responsive. AngularJS provides you built-in validation directives to achieve form validation and they
are based on the HTML5 form validators. You can also create your own custom validators.

Here is a list of angularjs directive which can be apply on a input field to validate it's value.
1. <inputtype="text"
2. ng-model="{ string }"
3. [name="{ string }"[
4. [ng-required="{ boolean }"]
5. [ng-minlength="{ number }"]
6. [ng-maxlength="{ number }"]
7. [ng-pattern="{ string }"]
8. [ng-change="{ string }"]>
9. </input>

Filter
Filters are used to format data before displaying it to the user. They can be used in view templates,
controllers, services and directives. There are some built-in filters provided by angularjs like as
Currency, Date, Number, OrderBy, Lowercase, Uppercase etc. You can also create your own filters.

Filter Syntax
1.

Filter Example
1. <script type="text/javascript">
2. {{ 14 | currency }} //returns $14.00
3. </script>

Services
Services are reusable singleton objects that are used to organize and share code across your app. They
can be injected into controllers, filters, directives.

$http Service
1.
2.
3.
4.
5.
6.
7.

<script>
$http.get('/products')
.success(function(data) {
$scope.products = data;
});
});
</script>

AngularJS offers several built-in services (like $http, $provide, $resource,$window,$parse) which always
start with $sign. You can also create your own services

Routing
AngularJS Routing helps you to divide your app into multiple views and bind different views to
Controllers. The magic of Routing is taken care by a angularjs service $routeProvider. $routeProvider
service provides method .when() and .otherwise() to define the routes for your app. Routing has
dependency on ngRoute module.
1. <script type="text/javascript">
2. var myApp = angular.module('myApp', ['ngRoute']);
3.
4. myApp.config(['$routeProvider',
5. function($routeProvider) {
6. $routeProvider.
7. when('/products', { //route
8. templateUrl: 'views/products.html',
9. controller: 'productController'
10. }).
11. when('/product/:productId', { //route with parameter
12. templateUrl: 'views/product.html',
13. controller: 'productController'
14. }).
15. otherwise({ //default route
16. redirectTo: '/index'
17. });
18. }]);
19. </script>

Dependency Injection
Dependency Injection (DI) is a software design pattern that deals with how components get hold of
their dependencies. AngularJS comes with a built-in dependency injection mechanism. You can divide
your angularjs app into multiple different types of components which angularjs can inject into each
other.

Dependency Annotation
There are following three ways of injecting dependencies into your code:
1. Implicitly from the function parameter names
1. <script type="text/javascript">
2. function MyController($scope, greeter) {
3. // ...
4. }
5. </script>
2. Using the $inject property annotation
1. <script type="text/javascript">
2. var MyController = function(renamed$scope, renamedGreeter) {
3. ...
4. }
5.
6. MyController['$inject'] = ['$scope', 'greeter'];

7. </script>
3. Using the inline array annotation
1. <script type="text/javascript">
2. someModule.factory('greeter', ['$window', function(renamed$window) {
3. // ...
4. }]);
5. </script>

Testing
AngularJS is designed to be testable so that you can test your AngularJS applications as easy as
possible. It also comes with an end-to-end and unit test runner setup.

A Look into AngularJS Compilation Process


Angular's HTML compiler allows you to teach the browser new HTML syntax. The compiler allows you
to attach new behaviors or attributes to any HTML element. Angular calls these behaviors as directives.

AngularJS Compilation
AngularJS compilation process takes place in the web browser; no server side or pre-compilation step
is involved. Angular use $compiler service to compile your Angular HTML page. The angular'
compilation process begins after your HTML page (static DOM) is fully loaded. It happens in two phases
:

1.

Compile

It traverse the DOM and collect all of the directives. The result is a linking function.

2.

Link

It combine the directives with a scope and produce a live view. Any changes in the scope model are
reflected in the view, and any user interactions with the view are reflected in the scope model.
The concept of compile and link comes from C, where you first compile the code and then link it to
actually execute it. The process is very much similar in AngularJS as well.

Comparing Angular template compilation with other


framework template compilation
If you have worked on templates in other java script framework/library like backbone and jQuery, they
process the template as a string and result as a string. You have to dumped this result string into the
DOM where you wanted it with .innerHTML()
AngularJS process the template in another way. It directly works on HTML DOM rather than strings
and manipulate it as required. It uses two way data-binding between model and view to sync your
data.

How angular's directives are compiled


It's important to note that Angular operates on DOM nodes rather than strings. Usually, you don't
notice this because when a html page loads, the web browser parses HTML into the DOM
automatically.
HTML compilation happens in three phases:
1. The $compile traverses the DOM and looks for directives. For each directive it finds, it adds it to a list
of directives.
2. Once the entire DOM has been traversed, it will sort that list of directives by their priority. Then, each
directives own compile function are executed, giving each directive the chance to modify the DOM
itself. Each compile function returns a linking function, which is then composed into a combined linking
function and returned.
3. $compile links the template with the scope by calling the combined linking function from the previous
step. This in turn will call the linking function of the individual directives, registering listeners on the
elements and setting up $watchs with the scope as each directive is configured to do.

The pseudo code for the above process is given below:


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.

var $compile = ...; // injected into your code


var scope = ...;
var parent = ...; // DOM element where the compiled template can be appended
var html = '<div ng-bind="exp"></div>';
// Step 1: parse HTML into DOM element
var template = angular.element(html);
// Step 2: compile the template
var linkFn = $compile(template);
// Step 3: link the compiled template with the scope.
var element = linkFn(scope);
// Step 4: Append to DOM (optional)
parent.appendChild(element);

AngularJS Form Validation with Bootstrap


AngularJS form validation enables you to develop a modern HTML5 form that is interactive and
responsive. AngularJS provides you built-in validation directives to to validate form client side. This
makes your life pretty easy to handle client-side form validations without adding a lot of extra effort.
AngularJS form validation are based on the HTML5 form validators.

AngularJS directives for form validation


Here is a list of angularjs directive which can be apply on a input field to validate it's value.
1. <input type="text"

2. ng-model="{ string }"


3. [name="{ string }"]
4. [ng-required="{ boolean }"]
5. [ng-minlength="{ number }"]
6. [ng-maxlength="{ number }"]
7. [ng-pattern="{ string }"]
8. [ng-change="{ string }"]>
9. </input>

The main advantage of using AngularJS form validation instead of HTML5 attributes based validation,
is that AngularJS way allows to mantain the two way data binding between model and view.

Custom Validation
AngularJS allows you to crate your own custom validation directives. For example, you want to
compare password and confirm password fields. To do this, you have to make a custom directive that
will fire whenever the password or confirmpassword changes.
1. <script>
2. //defining module
3. var myapp = angular.module('myapp', []);
4.
5. //creating custom directive
6. myapp.directive('ngCompare', function () {
7. return {
8. require: 'ngModel',
9. link: function (scope, currentEl, attrs, ctrl) {
10. var comparefield = document.getElementsByName(attrs.ngCompare)[0]; //getting f
irst element
11. compareEl = angular.element(comparefield);
12.
13. //current field key up
14. currentEl.on('keyup', function () {
15. if (compareEl.val() != "") {
16. var isMatch = currentEl.val() === compareEl.val();
17. ctrl.$setValidity('compare', isMatch);
18. scope.$digest();
19. }
20. });
21.
22. //Element to compare field key up
23. compareEl.on('keyup', function () {
24. if (currentEl.val() != "") {
25. var isMatch = currentEl.val() === compareEl.val();
26. ctrl.$setValidity('compare', isMatch);
27. scope.$digest();
28. }
29. });
30. }
31. }
32. });
33. </script>

Angular Form Properties


Angular provides properties on form which help you to get information about a form or it's inputs and
to validate them.

1.

$valid

It is a boolean property that tells whether the form or it's inputs are valid or not. If all containing form
and controls are valid, then it will be true, otherwise it will be false.
Syntax
1. formName.$valid
2. formName.inputFieldName.$valid

2.

$invalid

It is a boolean property that tells whether the form or it's inputs are invalid or not. If at least one
containing form and control is invalid then it will be true, otherwise it will be false.
Syntax
1. formName.$invalid
2. formName.inputFieldName.$invalid

3.

$pristine

It is a boolean property that tells whether the form or it's inputs are unmodified by the user or not. If
the form or it's inputs are unmodified by the user, then it will be true, otherwise it will be false.
Syntax
1. formName.inputFieldName.$pristine

4.

$dirty

It is a boolean property that is actually just reverse of pristine i.e. it tells whether the form or it's inputs
are modified by the user or not. If the form or it's inputs are modified by the user, then it will be true,
otherwise it will be false.
Syntax
1. formName.$dirty
2. formName.inputFieldName.$dirty

5.

$error

This is an object hash which contains references to all invalid controls or forms. It has all errors as keys:
where keys are validation tokens (such as required, url or email) and values are arrays of controls or
forms that are invalid with given error. For a control, If a validation fails then it will be true, otherwise
it will be false.
Syntax
1. formName.$error
2. formName.inputFieldName.$error

Angular Form Methods


Angular provides some methods to change a form state. These are available only for the form, not for
individual controls.

1.

$addControl()

This method registers a control with the form.

Syntax
1. formName.$addControl()

2.

$removeControl()

This method remove a control from the form.


Syntax
1. formName.$removeControl()

3.

$setDirty()

This method set the form to Dirty state.


Syntax
1. formName.$setDirty()

4.

$setPristine()

This method set the form to its pristine state.


Syntax
1. formName.$setPristine()

5.

$setValidity()

This method set the validity of a form control.


Syntax
1. formName.$setValidity()

Controlling Display of Error Messages


By default, angularjs validation error messages are shown as soon as the page is loaded. This doesn't
seems pretty at all. The error messages will be shown, when you will click on submit button or when
are interacting with the input. You can achieve this by checking button submit state or by checking
form input field $dirty property. So you have to write the code as shown below:
1. <script >
2. //Other code has been removed for clarity
3. // function to submit the form after all validation has occurred
4. $scope.submitForm = function () {
5.
6. // Set the 'submitted' flag to true
7. $scope.submitted = true;
8. //To DO
9. };
10. });
11. </script >
12.
13. <!-- Control display of error messages for NAME input -->
14. <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && (
userForm.name.$dirty || submitted)}">
15. <label>Name</label>
16. <input type="text" name="name" class="form-control" ng-model="user.name" plac
eholder="Your Name" ng-required="true">
17. <p ng-show="userForm.name.$invalid && (userForm.name.$dirty || submitted)" cl
ass="help-block">You name is required.</p>
18. </div>

A simple registration form using Angularjs


index.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>AngularJS & Bootstrap Form Validation</title>
5. <link href="css/bootstrap.css" rel="stylesheet" />
6. <link href="css/bootstrap-theme.css" rel="stylesheet" />
7. <script src="lib/angular.js"></script>
8. <script >
9. //defining module
10. var myapp = angular.module('myapp', []);
11.
12. //creating custom directive
13. myapp.directive('ngCompare', function () {
14. return {
15. require: 'ngModel',
16. link: function (scope, currentEl, attrs, ctrl) {
17. var comparefield = document.getElementsByName(attrs.ngCompare)[0]; //getting f
irst element
18. compareEl = angular.element(comparefield);
19.
20. //current field key up
21. currentEl.on('keyup', function () {
22. if (compareEl.val() != "") {
23. var isMatch = currentEl.val() === compareEl.val();
24. ctrl.$setValidity('compare', isMatch);
25. scope.$digest();
26. }
27. });
28.
29. //Element to compare field key up
30. compareEl.on('keyup', function () {
31. if (currentEl.val() != "") {
32. var isMatch = currentEl.val() === compareEl.val();
33. ctrl.$setValidity('compare', isMatch);
34. scope.$digest();
35. }
36. });
37. }
38. }
39. });
40.
41. // create angular controller
42. myapp.controller('mainController', function ($scope) {
43.
44. $scope.countryList = [
45. { CountryId: 1, Name: 'India' },
46. { CountryId: 2, Name: 'USA' }
47. ];
48.

49. $scope.cityList = [];


50.
51. $scope.$watch('user.country', function (newVal,oldVal) {
52.
53. if (newVal == 1)
54. $scope.cityList = [
55. { CountryId: 1, CityId: 1, Name: 'Noida' },
56. { CountryId: 1, CityId: 2, Name: 'Delhi' }];
57. else if (newVal == 2)
58. $scope.cityList = [
59. { CountryId: 2, CityId: 3, Name: 'Texas' },
60. { CountryId: 2, CityId: 4, Name: 'NewYork' }];
61. else
62. $scope.cityList = [];
63. });
64.
65. // function to submit the form after all validation has occurred
66. $scope.submitForm = function () {
67.
68. // Set the 'submitted' flag to true
69. $scope.submitted = true;
70.
71. if ($scope.userForm.$valid) {
72. alert("Form is valid!");
73. }
74. else {
75. alert("Please correct errors!");
76. }
77. };
78. });
79.
80. </script>
81. </head>
82. <body ng-app="myapp" ng-controller="mainController">
83. <div class="container">
84. <div class="col-sm-8 col-sm-offset-2">
85.
86. <!-- PAGE HEADER -->
87. <div class="page-header"><h1>AngularJS Form Validation</h1></div>
88.
89. <!-- FORM : YOU CAN DISABLE, HTML5 VALIDATION BY USING "novalidate" ATTRIBUTE
-->
90. <form name="userForm" ng-submit="submitForm()" novalidate>
91.
92. <!-- NAME -->
93. <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && (
userForm.name.$dirty || submitted)}">
94. <label>Name</label>
95. <input type="text" name="name" class="form-control" ng-model="user.name" plac
eholder="Your Name" ng-required="true">
96. <p ng-show="userForm.name.$error.required && (userForm.name.$dirty || submitt
ed)" class="help-block">You name is required.</p>
97. </div>
98.
99. <!-- USERNAME -->

100. <div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid


&& (userForm.username.$dirty || submitted)}">
101. <label>Username</label>
102. <input type="text" name="username" class="form-control" ng-model="user.usern
ame" placeholder="Your Username" ng-minlength="3" ng-maxlength="8" ng-required
="true">
103. <p ng-show="userForm.username.$error.required && (userForm.username.$dirty |
| submitted)" class="help-block">You username is required.</p>
104. <p ng-show="userForm.username.$error.minlength && (userForm.username.$dirty
|| submitted)" class="help-block">Username is too short.</p>
105. <p ng-show="userForm.username.$error.maxlength && (userForm.username.$dirty
|| submitted)" class="help-block">Username is too long.</p>
106. </div>
107.
108. <!-- PASSWORD -->
109. <div class="form-group" ng-class="{ 'has-error' : userForm.password.$invalid
&& (userForm.password.$dirty || submitted)}">
110. <label>Password</label>
111. <input type="Password" name="password" class="form-control" ng-model="user.p
assword" placeholder="Your Password" ng-required="true">
112. <p ng-show="userForm.password.$error.required && (userForm.password.$dirty |
| submitted)" class="help-block">Your password is required.</p>
113. </div>
114.
115. <!-- CONFIRM PASSWORD -->
116. <div class="form-group" ng-class="{ 'has-error' : userForm.confirmPassword.$
invalid && (userForm.confirmPassword.$dirty || submitted)}">
117. <label>Confirm Password</label>
118. <input type="Password" name="confirmPassword" class="form-control" ng-model=
"user.confirmPassword" placeholder="Confirm Your Password" ng-compare="passwor
d" ng-required="true">
119. <p ng-show="userForm.confirmPassword.$error.required && (userForm.confirmPas
sword.$dirty || submitted)" class="help-block">Your confirm password is requir
ed.</p>
120. <p ng-show="userForm.confirmPassword.$error.compare && (userForm.confirmPass
word.$dirty || submitted)" class="help-block">Confirm password doesnot match.<
/p>
121. </div>
122.
123. <!-- EMAIL -->
124. <div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid &&
(userForm.email.$dirty || submitted)}">
125. <label>Email</label>
126. <input type="email" name="email" class="form-control" ng-model="user.email"
placeholder="Your Email Address" ng-required="true">
127. <p ng-show="userForm.email.$error.required && (userForm.email.$dirty || subm
itted)" class="help-block">Email is required.</p>
128. <p ng-show="userForm.email.$error.email && (userForm.email.$dirty || submitt
ed)" class="help-block">Enter a valid email.</p>
129. </div>
130.
131. <!-- CONTACTNO -->
132. <div class="form-group" ng-class="{ 'has-error' : userForm.contactno.$invali
d && (userForm.contactno.$dirty || submitted) }">
133. <label>ContactNo</label>

134. <input type="text" name="contactno" class="form-control" ng-model="user.cont


actno" placeholder="Your Contact No" ng-pattern="/^[789]\d{9}$/" maxlength="10
">
135. <p ng-show="userForm.contactno.$error.pattern && (userForm.contactno.$dirty
|| submitted)" class="help-block">Enter a valid contactno.</p>
136. </div>
137.
138. <!-- COUNTRY -->
139. <div class="form-group" ng-class="{ 'has-error' : userForm.country.$invalid
&& (userForm.country.$dirty || submitted)}">
140. <label>Country</label>
141. <select name="country" class="form-control"
142. ng-model="user.country"
143. ng-options="country.CountryId as country.Name for country in countryList"
144. ng-required="true">
145. <option value=''>Select</option>
146. </select>
147. <p ng-show="userForm.country.$error.required && (userForm.country.$dirty ||
submitted)" class="help-block">Select country.</p>
148. </div>
149.
150. <!-- CITY -->
151. <div class="form-group" ng-class="{ 'has-error' : userForm.city.$invalid &&
(userForm.city.$dirty || submitted)}">
152. <label>City</label>
153. <select name="city" class="form-control"
154. ng-model="user.city"
155. ng-options="city.CityId as city.Name for city in cityList"
156. ng-required="true">
157. <option value=''>Select</option>
158. </select>
159. <p ng-show="userForm.city.$error.required && (userForm.city.$dirty || submit
ted)" class="help-block">Select city.</p>
160. </div>
161.
162. <!-- TERMS & CONDITIONS -->
163. <div class="form-group" ng-class="{ 'has-error' : userForm.terms.$invalid &&
(userForm.terms.$dirty || submitted)}">
164. <label>Accept Terms & Conditions</label>
165. <input type="checkbox" value="" name="terms" ng-model="user.terms" ng-requir
ed="true" />
166. <p ng-show="userForm.terms.$error.required && (userForm.terms.$dirty || subm
itted)" class="help-block">Accept terms & conditions.</p>
167. </div>
168.
169. <!-- ng-disabled FOR ENABLING AND DISABLING SUBMIT BUTTON -->
170. <!--<button type="submit" class="btn btn-primary" ng-disabled="userForm.$inv
alid">Register</button>-->
171. <button type="submit" class="btn btn-primary">Register</button>
172. </form>
173. </div>
174. </div>
175. <br />
176. </body>
177. </html>

How it works..

What do you think?


I hope this article will help you to understand AngularJS form validation. I would like to have feedback
from my blog readers. Your valuable feedback, question, or comments about this article are always
welcome.

AngularJS CRUD Operations with WebAPI, EF


and Bootstrap
In previous article, you have learned about AngularJS Form Validation with Bootstrap. This article will
demonstrate, how to create an HTML5 app with CRUD (Create, Read, Update, Delete) Operations using
AngularJS, WebAPI, Entity Framework code first and Bootstrap.

Creating Data Model and DataContext using Entity


Framework
Suppose you have following data model and DataContext classes in EF.
1. public class User
2. {
3. public int UserId { get; set; }
4.
5. [Required]
6. [MaxLength(50)]
7. [Column(TypeName = "varchar")]
8. public string Name { get; set; }
9.
10. [Required]
11. [MaxLength(200)]
12. [Column(TypeName = "varchar")]
13. public string Address { get; set; }
14.
15. [Column(TypeName = "varchar")]
16. [MaxLength(15)]
17. public string ContactNo { get; set; }
18. }
19.
20. public class DataContext : DbContext
21. {
22. public DataContext()
23. : base("DefaultConnection")
24. {
25.
26. }
27.
28. public DbSet<User> Users { get; set; }
29. }

Now migrate your data model class into SQL Server database by using EF code first database migration.
For more help refer this link Understanding Entity Framework Code First Migrations

Creating CRUD Operations using Web API and Entity


Framework
1.
2.
3.
4.
5.
6.
7.
8.
9.

public class UserServiceController : ApiController


{
DataContext context = new DataContext();
[HttpPost]
public int AddUser(User user)
{
context.User.Add(user);
context.SaveChanges();

10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.

return user.UserId;
}
[HttpGet]
public User GetUser(int id)
{
User user = context.User.Find(id);
return user;
}
[HttpGet]
public List GetUsersList()
{
return context.User.ToList();
}
[HttpPut]
public void ModifyUser(User user, int id)
{
if (user.UserId == id)
{
context.Entry(user).State = EntityState.Modified;
context.SaveChanges();
}
}
[HttpDelete]
public void DeleteUser(int id)
{
User user = context.User.Find(id);
if (user != null)
{
context.User.Remove(user);
context.SaveChanges();
}
}
}

Creating CRUD Operations using AngularJS and Bootstrap


Defining AngularJS Module and Controller
1. var app = angular.module('userApp', []);
2. var baseAddress = 'http://localhost:49595/MobileService/api/UserService/';
3. var url = "";
4.
5. app.factory('userFactory', function ($http) {
6. return {
7. getUsersList: function () {
8. url = baseAddress + "GetUsersList";
9. return $http.get(url);

10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.

},
getUser: function (user) {
url = baseAddress + "GetUser/" + user.UserId;
return $http.get(url);
},
addUser: function (user) {
url = baseAddress + "AddUser";
return $http.post(url, user);
},
deleteUser: function (user) {
url = baseAddress + "DeleteUser/" + user.UserId;
return $http.delete(url);
},
updateUser: function (user) {
url = baseAddress + "ModifyUser/" + user.UserId;
return $http.put(url, user);
}
};
});

app.controller('userController', function PostController($scope, userFactory)


{
31. $scope.users = [];
32. $scope.user = null;
33. $scope.editMode = false;
34.
35. //TO DO: CRUD Opeartions
36. });

Create Operation
1.
2.

<script>
app.controller('userController', function PostController($scope, userFactory)
{
3. $scope.users = [];
4. $scope.user = null;
5. $scope.editMode = false;
6.
7. //Other code has been removed for clarity
8.
9. // add User
10. $scope.add = function () {
11. var currentUser = this.user;
12. if (currentUser != null && currentUser.Name != null && currentUser.Address &&
currentUser.ContactNo) {
13. userFactory.addUser(currentUser).success(function (data) {
14. $scope.addMode = false;
15. currentUser.UserId = data;
16. $scope.users.push(currentUser);
17.
18. //reset form
19. $scope.user = null;
20. // $scope.adduserform.$setPristine(); //for form reset

21.
22. $('#userModel').modal('hide');
23. }).error(function (data) {
24. $scope.error = "An Error has occured while Adding user! " + data.ExceptionMes
sage;
25. });
26. }
27. };
28.
29. //Model popup events
30. $scope.showadd = function () {
31. $scope.user = null;
32. $scope.editMode = false;
33. $('#userModel').modal('show');
34. };
35. $scope.cancel = function () {
36. $scope.user = null;
37. $('#userModel').modal('hide');
38. }
39. });
40. </script>

1. <p><a data-ng-click="showadd()" href="javascript:;" class="btn btn-primary">Ad


d New User</a></p>
2.
3. <div class="modal fade" id="userModel" tabindex="-1" role="dialog" aria-hidde
n="true">
4. <div class="modal-dialog">
5. <div class="modal-content">
6. <div class="modal-header">
7. <button type="button" class="close" data-dismiss="modal" aria-hidden="true">X
</button>
8. <h4 class="modal-title" id="myModalLabel" ng-hide="editMode">Add User</h4>
9. <h4 class="modal-title" id="myModalLabel" ng-show="editMode">Edit User</h4>
10. </div>
11. <div class="modal-body">
12. <form class="form-horizontal" role="form" name="adduserform">
13. <div class="form-group">

14. <label for="title" class="col-sm-2 control-label">Name</label>


15. <div class="col-sm-10">
16. <input type="text" data-ng-model="user.Name" class="form-control" id="title" p
laceholder="Your Name" required title="Enter your name" />
17. </div>
18. </div>
19. <div class="form-group">
20. <label for="title" class="col-sm-2 control-label">Address</label>
21. <div class="col-sm-10">
22. <input type="text" data-ng-model="user.Address" class="form-control" id="titl
e" placeholder="Your Address" required title="Enter your address" />
23. </div>
24. </div>
25. <div class="form-group">
26. <label for="title" class="col-sm-2 control-label">ContactNo</label>
27. <div class="col-sm-10">
28. <input type="text" data-ng-model="user.ContactNo" class="form-control" id="ti
tle" placeholder="Your ContactNo" required title="Enter your contactno" />
29. </div>
30. </div>
31. <div class="form-group">
32. <div class="col-sm-offset-2 col-sm-10">
33. <span data-ng-hide="editMode">
34. <input type="submit" value="Add" ng-disabled="adduserform.$invalid" data-ng-c
lick="add()" class="btn btn-primary" />
35. </span>
36. <span data-ng-show="editMode">
37. <input type="submit" value="Update" ng-disabled="adduserform.$invalid" data-n
g-click="update()" class="btn btn-primary" />
38. </span>
39. <input type="button" value="Cancel" data-ng-click="cancel()" class="btn btn-p
rimary" />
40. </div>
41. </div>
42. </form>
43. </div>
44. </div>
45. </div>
46. </div>

Retrieve Operation
1.
2.

<script>
app.controller('userController', function PostController($scope, userFactory)
{
3. $scope.users = [];
4. $scope.user = null;
5. $scope.editMode = false;
6.
7. //Other code has been removed for clarity
8.
9. //get User
10. $scope.get = function () {

11. $scope.user = this.user;


12. $('#viewModal').modal('show');
13. };
14. });
15. </script>
16.

1. <div class="modal fade" id="viewModal" tabindex="-1" role="dialog" aria-hidden


="true">
2. <div class="modal-dialog">
3. <div class="modal-content">
4. <div class="modal-header">
5. <button type="button" class="close" data-dismiss="modal" aria-hidden="true">X
</button>
6. <h4 class="modal-title" id="myModalLabel">View User</h4>
7. </div>
8. <div class="modal-body">
9. <form class="form-horizontal" role="form" name="viewuser">
10. <div class="form-group">
11. <label for="Name" class="col-sm-2 control-label">Name</label>
12. <div class="col-sm-10">
13.
14. </div>
15. </div>
16. <div class="form-group">
17. <label for="Address" class="col-sm-2 control-label">Address</label>
18. <div class="col-sm-10">
19.
20. </div>
21. </div>
22. <div class="form-group">
23. <label for="ContactNo" class="col-sm-2 control-label">ContactNo</label>
24. <div class="col-sm-10">
25.
26. </div>
27. </div>
28. </form>
29. </div>
30. <div class="modal-footer">

31. <button type="button" class="btn btn-default" data-dismiss="modal">Close</but


ton>
32. </div>
33. </div>
34. </div>
35. </div>

Update Operation
1.
2.

<script>
app.controller('userController', function PostController($scope, userFactory)
{
3. $scope.users = [];
4. $scope.user = null;
5. $scope.editMode = false;
6.
7. //Other code has been removed for clarity
8. //update user
9. $scope.update = function () {
10. var currentUser = this.user;
11. userFactory.updateUser(currentUser).success(function (data) {
12. currentUser.editMode = false;
13.
14. $('#userModel').modal('hide');
15. }).error(function (data) {
16. $scope.error = "An Error has occured while Updating user! " + data.ExceptionM
essage;
17. });
18. };
19.
20. $scope.showedit = function () {
21. $('#userModel').modal('show');
22. };
23.
24. $scope.cancel = function () {
25. $scope.user = null;
26. $('#userModel').modal('hide');
27. }
28. </script>

1.

<div class="modal fade" id="userModel" tabindex="-1" role="dialog" aria-hidde


n="true">
2. <div class="modal-dialog">
3. <div class="modal-content">
4. <div class="modal-header">
5. <button type="button" class="close" data-dismiss="modal" aria-hidden="true">X
</button>
6. <h4 class="modal-title" id="myModalLabel" ng-hide="editMode">Add User</h4>
7. <h4 class="modal-title" id="myModalLabel" ng-show="editMode">Edit User</h4>
8. </div>
9. <div class="modal-body">
10. <form class="form-horizontal" role="form" name="adduserform">
11. <div class="form-group">
12. <label for="title" class="col-sm-2 control-label">Name</label>
13. <div class="col-sm-10">
14. <input type="text" data-ng-model="user.Name" class="form-control" id="title" p
laceholder="Your Name" required title="Enter your name" />
15. </div>
16. </div>
17. <div class="form-group">
18. <label for="title" class="col-sm-2 control-label">Address</label>
19. <div class="col-sm-10">
20. <input type="text" data-ng-model="user.Address" class="form-control" id="titl
e" placeholder="Your Address" required title="Enter your address" />
21. </div>
22. </div>
23. <div class="form-group">
24. <label for="title" class="col-sm-2 control-label">ContactNo</label>
25. <div class="col-sm-10">
26. <input type="text" data-ng-model="user.ContactNo" class="form-control" id="ti
tle" placeholder="Your ContactNo" required title="Enter your contactno" />
27. </div>
28. </div>
29. <div class="form-group">
30. <div class="col-sm-offset-2 col-sm-10">
31. <span data-ng-hide="editMode">
32. <input type="submit" value="Add" ng-disabled="adduserform.$invalid" data-ng-c
lick="add()" class="btn btn-primary" />
33. </span>
34. <span data-ng-show="editMode">
35. <input type="submit" value="Update" ng-disabled="adduserform.$invalid" data-n
g-click="update()" class="btn btn-primary" />
36. </span>
37. <input type="button" value="Cancel" data-ng-click="cancel()" class="btn btn-p
rimary" />
38. </div>
39. </div>
40. </form>
41. </div>
42. </div>
43. </div>
44. </div>

Delete Operation

1.
2.

<script>
app.controller('userController', function PostController($scope, userFactory)
{
3. $scope.users = [];
4. $scope.user = null;
5. $scope.editMode = false;
6.
7. //Other code has been removed for clarity
8. // delete User
9. $scope.delete = function () {
10. currentUser = $scope.user;
11. userFactory.deleteUser(currentUser).success(function (data) {
12. $('#confirmModal').modal('hide');
13. $scope.users.pop(currentUser);
14.
15. }).error(function (data) {
16. $scope.error = "An Error has occured while Deleting user! " + data.ExceptionM
essage;
17.
18. $('#confirmModal').modal('hide');
19. });
20. };
21.
22. //Model popup events
23. $scope.showconfirm = function (data) {
24. $scope.user = data;
25. $('#confirmModal').modal('show');
26. };
27. });
28. </script>
29.

1. <div class="modal fade" id="confirmModal" tabindex="-1" role="dialog" aria-hid


den="true">
2. <div class="modal-dialog">
3. <div class="modal-content">
4. <div class="modal-header">
5. <button type="button" class="close" data-dismiss="modal" aria-hidden="true">X
</button>
6. <h4 class="modal-title" id="myModalLabel">Confirm Action</h4>
7. </div>
8. <div class="modal-body">
9. Are you sure to delete?

10. </div>
11. <div class="modal-footer">
12. <button type="button" class="btn btn-default" data-ng-click="delete()">Ok</bu
tton>
13. <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</bu
tton>
14. </div>
15. </div>
16. </div>
17. </div>

Complete Code
index.html
1. <!DOCTYPE html>
2. <html xmlns="http://www.w3.org/1999/xhtml">
3. <head>
4. <title>AngularJS & Bootstrap CRUD Operations</title>
5. <link href="css/bootstrap.css" rel="stylesheet" />
6. <link href="css/bootstrap-theme.css" rel="stylesheet" />
7. <script src="lib/angular.js"></script>
8. <script src="lib/jquery-1.11.1.js"></script>
9. <script src="lib/bootstrap.js"></script>
10. </head>
11. <body>
12. <div class="container" style="padding-top:20px;">
13. <div ng-app="userApp" data-ng-controller="userController" class="container">
14. <div ng-show="error" class="alert alert-danger alert-dismissible" role="alert
">
15. <button type="button" class="close" data-dismiss="alert"><span aria-hidden="t
rue"></span><span class="sr-only">Close</span></button>
16. <p></p>
17. </div>
18.
19. <p><a data-ng-click="showadd()" href="javascript:;" class="btn btn-primary">A
dd New User</a></p>
20.
21. <div class="modal fade" id="userModel" tabindex="-1" role="dialog" aria-hidde
n="true">
22. <div class="modal-dialog">
23. <div class="modal-content">
24. <div class="modal-header">
25. <button type="button" class="close" data-dismiss="modal" aria-hidden="true">X
</button>
26. <h4 class="modal-title" id="myModalLabel" ng-hide="editMode">Add User</h4>
27. <h4 class="modal-title" id="myModalLabel" ng-show="editMode">Edit User</h4>
28. </div>
29. <div class="modal-body">
30. <form class="form-horizontal" role="form" name="adduserform">
31. <div class="form-group">
32. <label for="title" class="col-sm-2 control-label">Name</label>

33. <div class="col-sm-10">


34. <input type="text" data-ng-model="user.Name" class="form-control" id="title" p
laceholder="Your Name" required title="Enter your name" />
35. </div>
36. </div>
37. <div class="form-group">
38. <label for="title" class="col-sm-2 control-label">Address</label>
39. <div class="col-sm-10">
40. <input type="text" data-ng-model="user.Address" class="form-control" id="titl
e" placeholder="Your Address" required title="Enter your address" />
41. </div>
42. </div>
43. <div class="form-group">
44. <label for="title" class="col-sm-2 control-label">ContactNo</label>
45. <div class="col-sm-10">
46. <input type="text" data-ng-model="user.ContactNo" class="form-control" id="ti
tle" placeholder="Your ContactNo" required title="Enter your contactno" />
47. </div>
48. </div>
49. <div class="form-group">
50. <div class="col-sm-offset-2 col-sm-10">
51. <span data-ng-hide="editMode">
52. <input type="submit" value="Add" ng-disabled="adduserform.$invalid" data-ng-c
lick="add()" class="btn btn-primary" />
53. </span>
54. <span data-ng-show="editMode">
55. <input type="submit" value="Update" ng-disabled="adduserform.$invalid" data-n
g-click="update()" class="btn btn-primary" />
56. </span>
57. <input type="button" value="Cancel" data-ng-click="cancel()" class="btn btn-p
rimary" />
58. </div>
59. </div>
60. </form>
61. </div>
62. </div>
63. </div>
64. </div>
65.
66. <h1>Users List</h1>
67. <table class="table table-hover">
68. <tr>
69. <th>User ID</th>
70. <td>Name</td>
71. <th>Address</th>
72. <th>Contact No</th>
73. <th></th>
74. </tr>
75.
76. <tr data-ng-repeat="user in users">
77. <td><strong></strong></td>
78. <td>
79. <p></p>
80.
81. </td>

82. <td>
83. <p></p>
84.
85. </td>
86. <td>
87. <p></p>
88.
89. </td>
90. <td>
91. <p>
92. <a data-ng-click="get(user)" href="javascript:;">View</a> |
93. <a data-ng-click="edit(user)" href="javascript:;">Edit</a> |
94. <a data-ng-click="showconfirm(user)" href="javascript:;">Delete</a>
95. </p>
96.
97. </td>
98. </tr>
99. </table>
100. <hr />
101.
102. <div class="modal fade" id="viewModal" tabindex="-1" role="dialog" aria-hidd
en="true">
103. <div class="modal-dialog">
104. <div class="modal-content">
105. <div class="modal-header">
106. <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
X</button>
107. <h4 class="modal-title" id="myModalLabel">View User</h4>
108. </div>
109. <div class="modal-body">
110. <form class="form-horizontal" role="form" name="viewuser">
111. <div class="form-group">
112. <label for="Name" class="col-sm-2 control-label">Name</label>
113. <div class="col-sm-10">
114.
115. </div>
116. </div>
117. <div class="form-group">
118. <label for="Address" class="col-sm-2 control-label">Address</label>
119. <div class="col-sm-10">
120.
121. </div>
122. </div>
123. <div class="form-group">
124. <label for="ContactNo" class="col-sm-2 control-label">ContactNo</label>
125. <div class="col-sm-10">
126.
127. </div>
128. </div>
129. </form>
130. </div>
131. <div class="modal-footer">
132. <button type="button" class="btn btn-default" data-dismiss="modal">Close</bu
tton>
133. </div>

134. </div>
135. </div>
136. </div>
137.
138. <div class="modal fade" id="confirmModal" tabindex="-1" role="dialog" aria-h
idden="true">
139. <div class="modal-dialog">
140. <div class="modal-content">
141. <div class="modal-header">
142. <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
X</button>
143. <h4 class="modal-title" id="myModalLabel">Confirm Action</h4>
144. </div>
145. <div class="modal-body">
146. Are you sure to delete?
147. </div>
148. <div class="modal-footer">
149. <button type="button" class="btn btn-default" data-ng-click="delete()">Ok</b
utton>
150. <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</b
utton>
151. </div>
152. </div>
153. </div>
154. </div>
155. </div>
156. </div>
157. </body>
158. </html>

Script
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.

<script>
var app = angular.module('userApp', []);
var baseAddress = 'http://localhost:49595/MobileService/api/UserService/';
var url = "";
app.factory('userFactory', function ($http) {
return {
getUsersList: function () {
url = baseAddress + "GetUsersList";
return $http.get(url);
},
getUser: function (user) {
url = baseAddress + "GetUser/" + user.UserId;
return $http.get(url);
},
addUser: function (user) {
url = baseAddress + "AddUser";
return $http.post(url, user);
},
deleteUser: function (user) {
url = baseAddress + "DeleteUser/" + user.UserId;

22.
23.
24.
25.
26.
27.
28.
29.
30.
31.

return $http.delete(url);
},
updateUser: function (user) {
url = baseAddress + "ModifyUser/" + user.UserId;
return $http.put(url, user);
}
};
});

app.controller('userController', function PostController($scope, userFactory)


{
32. $scope.users = [];
33. $scope.user = null;
34. $scope.editMode = false;
35.
36. //get User
37. $scope.get = function () {
38. $scope.user = this.user;
39. $('#viewModal').modal('show');
40. };
41.
42. //get all Users
43. $scope.getAll = function () {
44. userFactory.getUsersList().success(function (data) {
45. $scope.users = data;
46. }).error(function (data) {
47. $scope.error = "An Error has occured while Loading users! " + data.ExceptionM
essage;
48. });
49. };
50.
51. // add User
52. $scope.add = function () {
53. var currentUser = this.user;
54. if (currentUser != null && currentUser.Name != null && currentUser.Address &&
currentUser.ContactNo) {
55. userFactory.addUser(currentUser).success(function (data) {
56. $scope.addMode = false;
57. currentUser.UserId = data;
58. $scope.users.push(currentUser);
59.
60. //reset form
61. $scope.user = null;
62. // $scope.adduserform.$setPristine(); //for form reset
63.
64. $('#userModel').modal('hide');
65. }).error(function (data) {
66. $scope.error = "An Error has occured while Adding user! " + data.ExceptionMes
sage;
67. });
68. }
69. };
70.
71. //edit user
72. $scope.edit = function () {

73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.

$scope.user = this.user;
$scope.editMode = true;
$('#userModel').modal('show');
};
//update user
$scope.update = function () {
var currentUser = this.user;
userFactory.updateUser(currentUser).success(function (data) {
currentUser.editMode = false;

$('#userModel').modal('hide');
}).error(function (data) {
$scope.error = "An Error has occured while Updating user! " + data.ExceptionM
essage;
87. });
88. };
89.
90. // delete User
91. $scope.delete = function () {
92. currentUser = $scope.user;
93. userFactory.deleteUser(currentUser).success(function (data) {
94. $('#confirmModal').modal('hide');
95. $scope.users.pop(currentUser);
96.
97. }).error(function (data) {
98. $scope.error = "An Error has occured while Deleting user! " + data.ExceptionM
essage;
99.
100. $('#confirmModal').modal('hide');
101. });
102. };
103.
104. //Model popup events
105. $scope.showadd = function () {
106. $scope.user = null;
107. $scope.editMode = false;
108. $('#userModel').modal('show');
109. };
110.
111. $scope.showedit = function () {
112. $('#userModel').modal('show');
113. };
114.
115. $scope.showconfirm = function (data) {
116. $scope.user = data;
117. $('#confirmModal').modal('show');
118. };
119.
120. $scope.cancel = function () {
121. $scope.user = null;
122. $('#userModel').modal('hide');
123. }
124.
125. // initialize your users data

126.
127.
128.

$scope.getAll();
});
</script>

What do you think?


I hope you will enjoy the article while working with AngularJS and ASP.NET WebAPI. I would like to
have feedback from my blog readers. Your valuable feedback, question, or comments about this article
are always welcome.

Understanding
AngularJS

Dependency

Injection

in

Dependency Injection (DI) is a software design pattern that allows you to remove hard coded
dependencies between software components. It allows you to develop loosely coupled components
by injecting dependencies either at compile time or run time.
AngularJS comes with a built-in dependency injection mechanism. Using Angular you can divide your
apps into multiple components which can be inject into each other by using AngularJS dependency
injection mechanism.

Methods to inject dependency in AngularJS


There are three ways to inject dependencies into your AngularJS components:

1.

The function parameter

This is the easiest way to inject dependencies into your code. You have to just pass the dependencies
as function parameters.
In this method, Angular read the name of the passing parameters, and if those names are already
registered as services, it will call your function when its invoked with those parameters.
1. <script type="text/javascript">
2. function MyController ($scope,$location) {
3. $scope.name = 'dotnet-tricks.com';
4. }
5. </script>

2.

The $inject property

The $inject property is an array of service names to inject. Hence defined your dependencies within
$inject array. Also, the order of the values in the $inject array must match the order of the parameters
to inject.
1. <script type="text/javascript">
2. var MyController = function(myscope, mylocation) {
3. myscope.name='dotnet-tricks.com';
4. }
5.
6. MyController['$inject'] = ['$scope', '$location'];
7. </script>

In the above code snippet, the $scope will be injected into myscope and $location into mylocation.
Hence, parameters matching will be based on the order of values in the $inject array and it doesnt
matter what is the name of the parameters.

3.

1.
2.
3.
4.
5.

The inline array

You can also inject dependencies by using an inline array which will contain the dependencies.
1. <script type="text/javascript">
2. var MyController = ['$scope','$location',function MyController (scope, loc
ation) {
3. scope.name = 'dotnet-tricks.com';
4. }];
5.
6. //OR
7. var app=angular.module('app',[]);
8. app.controller('MyController',['$scope','$location',function MyController
(scope, location) {
9. scope.name = 'dotnet-tricks.com';
10. }]);
11. </script>
AngularJS has the following core types of objects and components which can be injected into each
other using AngularJS dependency injection mechanism.
Value
Factory
Service
Provider
Constant

Understanding AngularJS $watch(), $digest()


and $apply()
AngularJS has a powerful data binding mechanism. When you do changes in a variable on the $scope
object within your view, the $scope object auto-magically updates itself. Similarly, whenever the
$scope object changes, the view updates itself with the new value. AngularJS handle data-binding
mechanism with the help of three powerful functions: $watch(), $digest() and $apply(). Most of the
time AngularJS will call the $scope.$watch() and $scope.$digest() functions for you, but in some cases
you may have to call these functions yourself to update new values. Therefore it is really good to know
how they work.

$watch()
The $scope.watch() function is used to observe changes in a variable on the $scope. It accepts three
parameters : expression, listener and equality object where listener and equality object are optional
parameters.
1. <!DOCTYPE html>

2. <html>
3. <head>
4. <title>AngularJS Watch</title>
5. <script src="lib/angular.js"></script>
6. <script>
7. var myapp = angular.module("myapp", []);
8. var myController = myapp.controller("myController", function ($scope) {
9. $scope.name = 'dotnet-tricks.com';
10. $scope.counter = 0;
11. $scope.$watch('name', function (newValue, oldValue) {
12. $scope.counter = $scope.counter + 1;
13. });
14. });
15. </script>
16.
17. </head>
18. <body ng-app="myapp" ng-controller="myController">
19. <input type="text" ng-model="name" />
20. <br />
21. Counter:
22. </body>
23. </html>

$digest()
The $scope.$digest() function iterates through all the watches in the $scope object, and its child $scope
objects (if it has any). When $digest() iterates over the watches, it checks if the value of the expression
has changed. If the value has changed, AngularJS calls the change callback(listener) with the new value
and the old value.
The $digest() function is called whenever AngularJS thinks it is necessary. For example, after a button
click, or after an AJAX call. You may have some corner cases where AngularJS does not call the $digest()
function for you. In that case you may have to call this function yourself.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>AngularJS Digest</title>
5. <script src="lib/angular.js"></script>
6. <script>
7. var myapp = angular.module("myapp", []);
8. var myController = myapp.controller("myController", function ($scope) {
9.
10. $scope.datetime = new Date();
11.
12. $scope.updateTime = function () {
13. $scope.datetime = new Date();
14. }
15.
16. document.getElementById("updateTimeButton").addEventListener('click', functio
n () {
17. console.log("update time clicked");
18. $scope.datetime = new Date();

19.
20. console.log($scope.datetime);
21. });
22. });
23. </script>
24.
25. </head>
26. <body ng-app="myapp" ng-controller="myController">
27. <button ng-click="updateTime()">Update time - ng-click</button>
28. <button id="updateTimeButton">Update time</button>
29. <br />
30.
31. </body>
32. </html>

When you will click on second button, the data binding is not updated. Since $scope.$digest() is not
called after the second button's event listener is executed. In this way on clicking the second button
the time will be updated in the $scope.data.time variable, but the new time will never displayed.
To fix this issue you need to add a $scope.$digest() call to the second button event listener, like this:
1. <script type="text/javascript">
2. document.getElementById("updateTimeButton").addEventListener('click', function
() {
3. console.log("update time clicked");
4. $scope.datetime = new Date();
5.
6. //to update $scope
7. $scope.$digest();
8. console.log($scope.datetime);
9. });</script>

$apply()
Angular do auto-magically updates only those model changes which are inside AngularJS context.
When you do change in any model outside of the Angular context (like browser DOM events,
setTimeout, XHR or third party libraries), then you need to inform Angular of the changes by calling
$apply() manually. When the $apply() function call finishes AngularJS calls $digest() internally, so all
data bindings are updated.
In above example, instead of calling $digest() function inside the button listener function you can used
the $apply() function like this:
1.
2.

<script>
document.getElementById("updateTimeButton").addEventListener('click', functio
n () {
3. $scope.$apply(function () {
4. console.log("update time clicked");
5. $scope.datetime = new Date();
6.
7. console.log($scope.datetime);
8. });
9. });

10. </script>

Note
1. $digest() is faster than $apply(), since $apply() triggers watchers on the entire scope chain while
$digest() triggers watchers on the current scope and its children(if it has).
2. When error occurs in one of the watchers, $digest() can not handled errors via $exceptionHandler
service, In this case you have to handle exception yourself. While $apply() uses try catch block internally
to handle errors and if error occurs in one of the watchers then it passes errors to $exceptionHandler
service.

What do you think?


I hope you will enjoy the AngularJS $watch(), $digest() and $apply() functions while developing your
app with AngularJS. I would like to have feedback from my blog readers. Your valuable feedback,
question, or comments about this article are always welcome.

Understanding AngularJS Factory, Service and


Provider
In AngularJS, services are reusable singleton objects that are used to organize and share code across
your app. They can be injected into controllers, filters, directives. AngularJS provides you three ways :
service, factory and provider to create a service.

Factory
A factory is a simple function which allows you to add some logic before creating the object. It returns
the created object.

Syntax
1. app.factory('serviceName',function(){ return serviceObj;})

Creating service using factory method


1. <script>
2. //creating module
3. var app = angular.module('app', []);
4.
5. //define a factory using factory() function
6. app.factory('MyFactory', function () {
7.
8. var serviceObj = {};

9. serviceObj.function1 = function () {
10. //TO DO:
11. };
12.
13. serviceObj.function2 = function () {
14. //TO DO:
15. };
16.
17. return serviceObj;
18. });
19. </script>

When to use
It is just a collection of functions like a class. Hence, it can be instantiated in different controllers when
you are using it with constructor function.

Service
A service is a constructor function which creates the object using new keyword. You can add properties
and functions to a service object by using this keyword. Unlike factory, it doesnt return anything.

Syntax
1. app.service('serviceName',function(){})

Creating service using service method


1. <script>
2. //creating module
3. var app = angular.module('app', []);
4.
5. //define a service using service() function
6. app.service('MyService', function () {
7. this.function1 = function () {
8. //TO DO:
9. };
10.
11. this.function2 = function () {
12. //TO DO:
13. };
14. });
15. </script>

When to use
It is a singleton object. Use it when you need to share a single object across the application. For
example, authenticated user details.

Provider
A provider is used to create a configurable service object. It returns value by using $get() function.

Syntax
1.
2.
3.
4.
5.

//creating a service
app.provider('serviceName',function(){});
//configuring the service
app.config(function(serviceNameProvider){});

Creating service using provider method


1. <script>
2. //define a provider using provider() function
3. app.provider('configurableService', function () {
4. var name = '';
5. this.setName = function (newName) {
6. name = newName;
7. };
8. this.$get = function () {
9. return name;
10. };
11. });
12.
13. //configuring provider using config() function
14. app.config(function (configurableService) {
15. configurableService.setName('www.dotnet-tricks.com');
16. });
17. </script>

When to use
When you need to provide module-wise configuration for your service object before making it
available.

AngularJS : Factory, Service and Provider with example


1. <html>
2. <head>
3. <title>AngularJS Service Factory and Providers</title>
4. <script src="lib/angular.js"></script>
5. </head>
6. <body>
7. <div class="container" style="padding-top:20px;">
8. <div ng-app="myApp" ng-controller="myController">
9. <p>From Service: </p>
10. <p>From Factory: </p>

11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.

<p>From Provider: </p>


</div>
</div>
<script>
//defining module
var app = angular.module('myApp', []);
//defining service
app.service('myService', function () {
this.name = '';
this.setName = function (newName) {
this.name = newName;
return this.name;
};
});
//defining factory
app.factory('myFactory', function () {
var serviceObj = {};
serviceObj.name = '';
serviceObj.setName = function (newName) {
serviceObj.name = newName;
};
return serviceObj;
});
//defining provider
app.provider('configurable', function () {
var privateName = '';
this.setName = function (newName) {
privateName = newName;
};
this.$get = function () {
return {
name: privateName
};
};
});
//configuring provider
app.config(function (configurableProvider) {
configurableProvider.setName("Saksham Chauhan");
});

//defining controller
app.controller('myController', function ($scope, myService, myFactory, config
urable) {
57. $scope.serviceName = myService.setName("Saksham Chauhan");
58.
59. myFactory.setName("Saksham Chauhan");
60. $scope.factoryName = myFactory.name;
61.
62. $scope.providerName = configurable.name;
63. });
64. </script>

65. </body>
66. </html>

How it works...

What do you think?


I hope you will enjoy the AngularJS factory, service and provider functions while developing your app
with AngularJS. I would like to have feedback from my blog readers. Your valuable feedback, question,
or comments about this article are always welcome.

Understanding
$scope

AngularJS

$rootScope

and

Scope is an object that refers to the application model. It acts as a context for evaluating expressions.
Typically, it acts as a glue between controller and view. Scopes are hierarchical in nature and follow the
DOM structure of your angular app. AngularJS has two scope objects: $rootScope and $scope. Let's
have a look, how they work.

$scope
A $scope is a JavaScript object which is used for communication between controller and view. Basically,
$scope binds a view (DOM element) to the viewmodel and functions defined in a controller.

$rootScope
The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared
among all the components of an app. Hence it acts like a global variable. All other $scopes are children
of the $rootScope.

AngularJS : $rootScope and $scope with example


1. <!doctype html>
2. <html>
3. <body ng-app="myApp">
4. <div ng-controller="Ctrl1" style="border:2px solid blue; padding:5px">
5. Hello !
6. <br />
7. Hello !
8. (rootScope)
9. </div>
10. <br />
11. <div ng-controller="Ctrl2" style="border:2px solid green; padding:5px">
12. Hello !
13. <br />
14. Hey !
15. <br />
16. Hi ! (rootScope)
17. </div>
18. <script src="lib/angular.js"></script>
19. <script>
20. var app = angular.module('myApp', []);
21.
22. app.controller('Ctrl1', function ($scope, $rootScope) {
23. $scope.msg = 'World';
24. $rootScope.name = 'AngularJS';
25. });
26.
27. app.controller('Ctrl2', function ($scope, $rootScope) {
28. $scope.msg = 'Dot Net Tricks';
29. $scope.myName = $rootScope.name;

30. });
31. </script>
32. </body>
33. </html>

How it works...

Note
1. When you use ng-model with $rootScope objects then AngularJS updates those objects under a
specific $scope of a controller but not at global level $rootScope.
2. Create a private $scope for each controller to bind it to the view.

What do you think?


I hope you will enjoy the AngularJS: $rootScope and $scope while developing your app with AngularJS.
I would like to have feedback from my blog readers. Your valuable feedback, question, or comments
about this article are always welcome.

Understanding AngularJS Directive


AngularJS directives extend the HTML elements with new behaviors. AngularJS directive help you to
manipulate HTML elements, handle event, perform data binding, associate controllers/scope with a
view and many more things. AngularJS provide you some built-in directives like as ng-app, ngcontroller, ng-repeat, ng-model etc. to make it easy.
Basically, AngularJS directives are its core functions that get run when the DOM is compiled by the
compiler. These are start with the ng- prefix attributes.

AngularJS : A simple directive example


1. <div ng-app="app">
2. <input type="text" ng-model="name">
3. <div></div>

4. </div>

Invoking directive
AngularJS provides you four ways to invoke a directive from HTML. These are all equivalent in
AngularJS.

1.

Directive as an attribute

1. <div ng-directive></div>

2.

Directive as a CSS class


1. <div class="ng-directive: expression;"></div>

3.

Directive as an element
1. <ng-directive></ng-directive>

4.

Directive as a comment
1. <!-- directive: ng-directive expression -->

Invoking directive with name prefixes


You can also invoke a directive with name prefix like ng-,ng:,ng_,x-ng-,data-ng-. These are all
equivalent in AngularJS.
1.
2.
3.
4.
5.
6.

<input type="text" ng-model="directivename"/>


<div ng-bind="directivename"></div>
<div ng:bind="directivename"></div>
<div ng_bind="directivename"></div>
<div x-ng-bind="directivename"></div>
<div data-ng-bind="directivename"></div>

Note
Use the data-prefixed version (e.g. data-ng-bind for ngBind ) of directive, if you want to validate
your HTML controls value.

Creating a custom directive


AngularJS also allow you to create your own directives based on your requirements. There is no builtin directive for comparing password in angular. So you can create your own custom directive for
comparing password.

Creating Custom Directive Syntax


1. <script>
2. //creating custom directive syntax
3. myApp.directive("myDir", function () {
4. return {

5.

restrict: "E", //define directive type like E = element, A = attribute, C = c


lass, M = comment
6. scope: { //create a new child scope or an isolate scope
7.
8. //@ reads the attribute value,
9. //= provides two-way binding,
10. //& works with functions
11.
12. title: '@'
13. },
14. template: "<div></div>",// define HTML markup
15. templateUrl: 'mytemplate.html', //path to the template, used by the directive
16. replace: true | false, // replace original markup with template yes/no
17. transclude: true | false, // copy original HTML content yes/no
18. controller: function (scope) { //define controller, associated with the direc
tive template
19. //TODO:
20. },
21. link: function (scope, element, attrs, controller) {//define function, used f
or DOM manipulation
22. //TODO:
23. }
24. }
25. });
26. </script>

Creating custom directive for comparing textbox values


1. <script>
2. //defining module
3. var myapp = angular.module('myApp', []);
4.
5. //creating custom directive
6. myapp.directive('ngCompare', [function () {
7. return {
8. require: 'ngModel',
9. link: function (scope, elem, attrs, ctrl) {
10. var firstfield = "#" + attrs.ngCompare;
11.
12. //second field key up
13. elem.on('keyup', function () {
14. scope.$apply(function () {
15. var isMatch = elem.val() === $(firstfield).val();
16. ctrl.$setValidity('valueMatch', isMatch);
17. });
18. });
19.
20. //first field key up
21. $(firstfield).on('keyup', function () {
22. scope.$apply(function () {
23. var isMatch = elem.val() === $(firstfield).val();
24. ctrl.$setValidity('valueMatch', isMatch);
25. });

26. });
27. }
28. }
29. }]);
30. </script>

AngularJS : Creating custom directive with example


1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>AngularJS Custom Directive</title>
5. <link href="css/bootstrap.css" rel="stylesheet" />
6. <link href="css/bootstrap-theme.css" rel="stylesheet" />
7. <script src="lib/jquery-1.11.1.js"></script>
8. <script src="lib/angular.js"></script>
9. </head>
10. <body>
11. <div ng-app="myApp" ng-controller="mainController">
12. <br />
13. <div class="container">
14. <form name="userForm" ng-submit="submitForm()" novalidate>
15. <h2>AngularJS Custom Directive (comparing input values)</h2>
16.
17. <!-- EMAIL -->
18. <div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid}">
19. <label>Email</label>
20. <input type="email" name="email" class="form-control" ng-model="user.email" p
laceholder="Your Email Address" ng-required="true">
21. <p ng-show="userForm.email.$error.required" class="help-block">Email is requi
red.</p>
22. <p ng-show="userForm.email.$error.email" class="help-block">Enter a valid ema
il.</p>
23. </div>
24.
25. <!-- Password -->
26. <div class="form-group" ng-class="{ 'has-error' : userForm.password.$invalid}
">
27. <label>Password</label>
28. <input type="Password" name="password" id="password" class="form-control" ngmodel="user.password" placeholder="Your Password" ng-required="true">
29. <p ng-show="userForm.password.$invalid" class="help-block">Your password is r
equired.</p>
30. </div>
31.
32. <!-- Confirm Password -->
33. <div class="form-group" ng-class="{ 'has-error' : userForm.confirmPassword.$i
nvalid}">
34. <label>Confirm Password</label>
35. <input type="Password" name="confirmPassword" class="form-control" ng-model="
user.confirmPassword" placeholder="Confirm Your Password" ng-compare="password
" ng-required="true">

36. <p ng-show="userForm.confirmPassword.$error.required" class="help-block">Your


confirm password is required.</p>
37. <p ng-show="userForm.confirmPassword.$error.valueMatch && !userForm.confirmPa
ssword.$error.required" class="help-block">Confirm password doesnot match.</p>
38. </div>
39.
40. <button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid"
>Register</button>
41. </form>
42. </div>
43. </div>
44.
45. <script>
46. //defining module
47. var myapp = angular.module('myApp', []);
48.
49. //creating custom directive
50. myapp.directive('ngCompare', [function () {
51. return {
52. require: 'ngModel',
53. link: function (scope, elem, attrs, ctrl) {
54. var firstfield = "#" + attrs.ngCompare;
55.
56. //second field key up
57. elem.on('keyup', function () {
58. scope.$apply(function () {
59. var isMatch = elem.val() === $(firstfield).val();
60. ctrl.$setValidity('valueMatch', isMatch);
61. });
62. });
63.
64. //first field key up
65. $(firstfield).on('keyup', function () {
66. scope.$apply(function () {
67. var isMatch = elem.val() === $(firstfield).val();
68. ctrl.$setValidity('valueMatch', isMatch);
69. });
70. });
71. }
72. }
73. }]);
74.
75. // create angular controller
76. myapp.controller('mainController', function ($scope) {
77.
78. // function to submit the form
79. $scope.submitForm = function () {
80.
81. // check to make sure the form is completely valid
82. if ($scope.userForm.$valid) {
83. alert('form is submitted');
84. }
85. };
86. });
87. </script>

88. </body>
89. </html>

How it works...

What do you think?


I hope you will enjoy the AngularJS directive while developing your app with AngularJS. I would like to
have feedback from my blog readers. Your valuable feedback, question, or comments about this article
are always welcome.

Understanding AngularJS Templates


In Angular, templates are the views with the HTML enriched by Angular elements like directive and
attributes. Templates are used to display the information from the model and controller that a user
sees in his browser. An angular templates can have Directive, HTML markup, CSS, Filters, Expressions
and Form controls.

A simple Angular Template


1. <html ng-app>
2. <body ng-controller="MyController">
3. <input ng-model="name" value="dotnet-tricks.com">
4. <br/>
5. Input Value is :
6. <button ng-click="changeValue()">Click me!</button>
7. <script src="angular.js">
8. </body>
9. </html>

Types of Templates
There are two types of templates :

1.

Static Templates

A static template is defined by using script tag. It must has an id attribute with a unique value and
a typeattribute with value text/ng-template. Also, a static template must be inside the scope of the
ng-app directive otherwise it will be ignored by Angular.
1. <script type="text/ng-template" id="person.html">
2. {{person.name}} : {{person.address}}
3. </script>
A static template can be rendered by using ng-include directive.
4. <div ng-include="'person.html'"></div>

Full Example of Static Template

5. <!DOCTYPE html>
6. <html>
7. <head>
8. <title>AngularJS Static Templates</title>
9. <script src="lib/angular.js"></script>
10. <script>
11. //defining module
12. var app = angular.module('app', []);
13.
14. app.controller("myController", function ($scope) {
15. $scope.person = { name: "Deepak Chauhan", address: "Delhi" };
16. });
17.
18. app.controller("homeController", function ($scope) {
19. $scope.persons = [{ name: "Deepak Chauhan", address: "Delhi" }, { name: "
Shailendra Chauhan", address: "Noida" }, { name: "Kuldeep Chauhan", addres
s: "Gurgaon" }]
20. });
21.
22. </script>
23.
24.</head>
25.<body ng-app="app">
26. <h1>AngularJS : Static Templates</h1>
27. <!--It should be the part of ng-app directive-->
28. <script type="text/ng-template" id="person.html">
29. {{person.name}} : {{person.address}}
30. </script>
31.
32. <div ng-controller="myController">
33. <h1>myController</h1>
34. <!--Please not the single quotes around person.html. The value of the nginclude is an expression and person.html is a string value, so put single q
uotes around it.-->
35. <div ng-include="'person.html'"></div>
36. </div>

2.

37.
38. <div ng-controller="homeController">
39. <h1>homeController</h1>
40. <div ng-repeat="person in persons" ng-include="'person.html'"></div>
41. </div>
42.</body>
43.</html>

Dynamic Templates

A dynamic template is an html page which is compiled and rendered by Angular on demand. The
above static template can be created as a HTML page within templates folder of your app like as:

person.html

1. :
A dynamic template can be rendered by using ng-include directive.
2. <div ng-include="'templates/person.html'"></div>

Full Example of Dynamic Template

3. <!DOCTYPE html>
4. <html>
5. <head>
6. <title>AngularJS Dynamic Templates</title>
7. <script src="lib/angular.js"></script>
8. <script>
9. //defining module
10. var app = angular.module('app', []);
11.
12. app.controller("myController", function ($scope) {
13. $scope.person = { name: "Deepak Chauhan", address: "Delhi" };
14. });
15.
16. app.controller("homeController", function ($scope) {
17. $scope.persons = [{ name: "Deepak Chauhan", address: "Delhi" }, { name: "
Shailendra Chauhan", address: "Noida" }, { name: "Kuldeep Chauhan", addres
s: "Gurgaon" }]
18. });
19.
20. </script>
21.
22.</head>
23.<body ng-app="app">
24. <h1>AngularJS : Dynamic Templates</h1>
25. <div ng-controller="myController">
26. <h1>myController</h1>
27. <!--Please not the single quotes around person.html. The value of the nginclude is an expression and person.html is a string value, so put single q
uotes around it.-->
28. <div ng-include="'templates/person.html'"></div>
29. </div>
30.
31. <div ng-controller="homeController">
32. <h1>homeController</h1>

33. <div ng-repeat="person in persons" ng-include="'templates/person.html'"><


/div>
34. </div>
35.</body>
36.</html>

person.html
37.

Note
Always put the single quotes around the name of template with ng-include directive, since it accept
an expression. Hence to indicate to Angular that template (person.html) is a string value you have to
put single quotes around it's name.

What do you think?


I hope you will enjoy the AngularJS Templates while developing your app with AngularJS. I would like
to have feedback from my blog readers. Your valuable feedback, question, or comments about this
article are always welcome.

Understanding AngularJS Routing


Routing is a mechanism which helps you to divide your single page application into multiple views and
bind these views to corresponding controllers. In this article, you will learn how to configure angular
routing.
An angular route is specified within the URL by using # sign and enables you to show a specific view.
Some example of angular routes are given below:
1.
2.
3.
4.

http://yourdomain.com/index.html#users
http://yourdomain.com/index.html#orders
http://yourdomain.com/index.html#books
http://yourdomain.com/index.html#games

AngularJS Route Module


The routing functionality is provided by the angular's ngRoute module, which is the part of angularroute.jsJavaScript file. Hence, include angular-route.js file into your AngularJS application for using
routing. You have to add ngRoute module as an dependent module as given below:
1. var app = angular.module("app", ['ngRoute']);

Configuring the $routeProvider


The routes in your angular application are declared with the help of $routeProvider which is the
provider of the $route service. The $routeProvider is configured in your app
module's config() function.

Syntax to configure Routing


1. <script>
2. appmodule.config(['$routeProvider',
3. function($routeProvider) {
4. $routeProvider.
5. when('/route1', {
6. templateUrl: 'template-1.html',
7. controller: 'RouteController1'
8. }).
9. when('/route2:param', {
10. templateUrl: 'template-2.html',
11. controller: 'RouteController2'
12. }).
13. otherwise({ // if no route paths matches
14. redirectTo: '/'
15. });
16. }]);
17. </script>
18.
19. <!-- And links should be defined as: -->
20.
21. <a href="#/route1">Route 1</a><br/>
22. <a href="#/route2:123">Route 2</a><br/>

The when() function takes a route path and a JavaScript object as parameters. The route path is
matched against the part of the URL after the # sign. The otherwise() function redirects to the
specified route if no route paths matches.

The ngView Directive


The ngView directive renders the template of the current route into the main layout (index.html) file.
Every time, when the current route changes, the ngView directive view changes based on the new
route path settings.
1. <div ng-view></div>

An Example of Routing
index.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>AngularJS Routing</title>
5. <script src="lib/angular.js"></script>
6. <script src="lib/angular-route.js"></script>
7.
8. <script>

9. var app = angular.module("app", ['ngRoute']);


10.
11. app.controller("homeController", function ($scope) {
12.
13. $scope.message = "Welcome to Home Page!";
14. });
15.
16. app.controller("aboutController", function ($scope) {
17.
18. $scope.message = "Welcome to About Page!";
19. });
20.
21. app.controller("contactController", function ($scope) {
22.
23. $scope.message = "Welcome to Contact Page!";
24. });
25.
26. app.config(['$routeProvider', function ($routeProvider) {
27. $routeProvider.when("/", {
28. templateUrl: "templates/pages/home.html",
29. controller: "homeController"
30. }).when("/about", {
31. templateUrl: "templates/pages/about.html",
32. controller: "aboutController"
33. }).when("/contact", {
34. templateUrl: "templates/pages/contact.html",
35. controller: "contactController"
36. }).otherwise({
37. redirectTo: 'index.html'
38. });
39. }]);
40.
41. </script>
42. </head>
43. <body ng-app="app">
44. <div>
45. <a href="#">Home</a> |
46. <a href="#contact">Contact</a> |
47. <a href="#about">About</a>
48. </div>
49. <div ng-view></div>
50. </body>
51. </html>

home.html
1. <h1>Home Page</h1>
2. <h2></h2>

about.html
1. <h1>About Page</h1>

2. <h2></h2>

contact.html
1. <h1>Contact Page</h1>
2. <h2></h2>

What do you think?


I hope you will enjoy the AngularJS Routing while developing your app with AngularJS. I would like to
have feedback from my blog readers. Your valuable feedback, question, or comments about this article
are always welcome.

Understanding AngularJS Bootstrap Process


Angular initializes automatically upon DOMContentLoaded event or when the angular.js script is
downloaded to the browser and the document.readyState is set to complete. At this point AngularJS
looks for the ng-app directive which is the root of angular app compilation and tells about AngularJS
part within DOM. When the ng-app directive is found then Angular will:
1. Load the module associated with the directive.
2. Create the application injector.
3. Compile the DOM starting from the ng-app root element.
This process is called auto-bootstrapping.

1. <html>
2. <body ng-app="myApp">
3. <div ng-controller="Ctrl">
4. Hello !
5. </div>
6.
7. <script src="lib/angular.js"></script>
8. <script>
9. var app = angular.module('myApp', []);
10. app.controller('Ctrl', function ($scope) {
11. $scope.msg = 'World';
12. });
13. </script>
14. </body>
15. </html>

Manual Bootstrap Process


You can manually initialized your angular app by using angular.bootstrap() function. This function
takes
the
modules
as
parameters
and
should
be
called
within angular.element(document).ready() function.
The
angular.element(document).ready()
function is fired when the DOM is ready for manipulation.
1. <html>
2. <body>

3. <div ng-controller="Ctrl">
4. Hello !
5. </div>
6. <script src="lib/angular.js"></script>
7.
8. <script>
9. var app = angular.module('myApp', []);
10. app.controller('Ctrl', function ($scope) {
11. $scope.msg = 'World';
12. });
13.
14. //manual bootstrap process
15. angular.element(document).ready(function () {
16. angular.bootstrap(document, ['myApp']);
17. });
18. </script>
19. </body>
20. </html>

Note
1. You should not use the ng-app directive when manually bootstrapping your app.
2. You should not mix up the automatic and manual way of bootstrapping your app.
3. Define modules, controller, services etc. before manually bootstrapping your app as defined in above
example.

What do you think?


I hope you will enjoy the AngularJS bootstrap process while developing your app with AngularJS. I
would like to have feedback from my blog readers. Your valuable feedback, question, or comments
about this article are always welcome.

Understanding jQLite or jQuery Lite


JQLite is a subset of jQuery that is built directly into AngularJS. jQLite provides you all the useful
features of jQuery. In fact it provides you limited features or functions of jQuery.
By default AngularJS use jQLite which is the subset of jQuery. If you want to use jQuery then simply
load the jQuery library before loading the AngularJS. By doing so, Angular will skip jQLite and will
started to use jQuery library.
Here is a table of supported jQuery methods by jQLite.
jQuery Method
Limitation, if any
addClass()
after()
append()

attr()
bind()
Does not support namespace, selectors and eventData
children
Does not support selectors
clone()
contents()
css()
data()
detach()
empty()
eq()
find()
Limited to lookups by tag name
hasClass()
html()
text()
Does not support selectors
on()
Does not support namespace, selectors and eventData
off()
Does not support namespace, selectors
one()
Does not support namespace, selectors
parent()
Does not support selectors
prepend()
prop

ready()
remove
removeAttr()
removeClass()
removeData()
replaceWith()
toggleClass()
triggerHandler()
Passes a dummy event object to handlers
unbind()
Does not support namespace
val()
wrap()

Accessing jQLite or jQuery with AngularJS


jQuery lite or the full jQuery library if available, can be accessed via the AngularJS code by using the
element() function in AngularJS. Basically, angular.element() is an alias for the jQuery function i.e.
1. angular.element() === jQuery() === $()
1. <html>
2. <head>
3. <script src="lib/angular.js"></script>
4. <script type="text/javascript">
5. var app = angular.module('app', []);
6. app.controller("mainCtrl", function ($scope, $element) {
7. $scope.clickme = function () {
8. var elem = angular.element(document.querySelector('#txtName'));
9. console.log(elem.val())// console the value of textbox
10. };
11. });
12. </script>
13. </head>
14. <body ng-app="app">
15. <div ng-controller="mainCtrl">
16. <input type="text" id="txtName" value="Shailendra Chauhan" />
17. <button type="button" ng-click="clickme()">Click me</button>
18. </div>
19. </body>
20. </html>

What do you think?


I hope you will enjoy the jQlite with AngularJS while developing your app with AngularJS. I would like
to have feedback from my blog readers. Your valuable feedback, question, or comments about this
article are always welcome.

Bootstrapping angular app based on multiple


modules
AngularJS is automatically initialized for one module. But sometimes, it is required to bootstrap for
multiple modules and it can be achieved by using two methods:

1. Automatic bootstrap (by combining multiple modules into


one module)
You can combine multiple modules into single modules and your angular app will be automatically
initialized for newly created module and other modules will act as dependent modules for newly
created module.
For example, suppose you have two modules: module1 and model2, and you have to initialize your
app automatically based on these two modules then you achieve this following way:
1. <html>
2. <head>
3. <title>Multiple modules bootstrap</title>
4. <script src="lib/angular.js"></script>
5. <script>
6. //module1
7. var app1 = angular.module("module1", []);
8. app1.controller("Controller1", function ($scope) {
9. $scope.name = "Shailendra Chauhan";
10. });
11.
12. //module2
13. var app2 = angular.module("module2", []);
14. app2.controller("Controller2", function ($scope) {
15. $scope.name = "Deepak Chauhan";
16. });
17.
18. //module3 dependent on module1 & module2

2.

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


20. </script>
21.</head>
22.<body>
23. <!--angularjs autobootstap process-->
24. <div ng-app="app">
25. <h1>Multiple modules bootstrap</h1>
26. <div ng-controller="Controller2">
27.
28. </div>
29. <div ng-controller="Controller1">
30.
31. </div>
32. </div>
33.</body>
34.</html>
35.

Manual bootstrap

You can manually bootstrap your app by using angular.bootstrap() function, for multiple modules.
The above example can be rewritten as for manual bootstrap process as given below:
1. <html>
2. <head>
3. <title>Multiple modules bootstrap</title>
4. <script src="lib/angular.js"></script>
5. <script>
6. //module1
7. var app1 = angular.module("module1", []);
8. app1.controller("Controller1", function ($scope) {
9. $scope.name = "Shailendra Chauhan";
10. });
11.
12. //module2
13. var app2 = angular.module("module2", []);
14. app2.controller("Controller2", function ($scope) {
15. $scope.name = "Deepak Chauhan";
16. });
17.
18. //manual bootstrap process
19. angular.element(document).ready(function () {
20. var div1 = document.getElementById('div1');
21. var div2 = document.getElementById('div2');
22.
23. //bootstrap div1 for module1 and module2
24. angular.bootstrap(div1, ['module1', 'module2']);
25.
26. //bootstrap div2 only for module1
27. angular.bootstrap(div2, ['module1']);
28. });
29. </script>
30.</head>
31.<body>

32. <!--angularjs autobootstap process-->


33. <div id="div1">
34. <h1>Multiple modules bootstrap</h1>
35. <div ng-controller="Controller1">
36.
37. </div>
38. <div ng-controller="Controller2">
39.
40. </div>
41. </div>
42.
43. <div id="div2">
44. <div ng-controller="Controller1">
45.
46. </div>
47. </div>
48.</body>
49.</html>

What do you think?


I hope you have got, how to bootstrap your angular app based on multiple modules. I would like to
have feedback from my blog readers. Your valuable feedback, question, or comments about this article
are always welcome.

Understanding scope inheritance in AngularJS


The $scope object used by views in AngularJS are organized into a hierarchy. There is a root scope,
and the $rootScope can has one or more child scopes. Each controller has its own $scope (which is a
child of the $rootScope), so whatever variables you create on $scope within controller, these variables
are accessible by the view based on this controller.

For example, suppose you have two controllers: ParentController and ChildController as given below:
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Angular Scope Inheritance</title>
5. <script src="lib/angular.js"></script>
6. <script>
7. var app = angular.module('ScopeChain', []);
8.
9. app.controller("parentController", function ($scope) {
10. $scope.managerName = 'Shailendra Chauhan';
11. $scope.$parent.companyName = 'Dot Net Tricks'; //attached to $rootScope
12. });
13. app.controller("childController", function ($scope, $controller) {
14. $scope.teamLeadName = 'Deepak Chauhan';
15. });
16. </script>
17. </head>
18. <body ng-app="ScopeChain">
19. <div ng-controller="parentController ">
20. <table style="border:2px solid #e37112">
21. <caption>Parent Controller</caption>
22. <tr>
23. <td>Manager Name</td>
24. <td></td>
25. </tr>
26. <tr>
27. <td>Company Name</td>
28. <td></td>
29. </tr>
30. <tr>
31. <td>
32. <table ng-controller="childController" style="border:2px solid #428bca">
33. <caption>Child Controller</caption>
34. <tr>
35. <td>Team Lead Name</td>
36. <td></td>
37. </tr>
38. <tr>
39. <td>Reporting To</td>
40. <td></td>
41. </tr>
42. <tr>
43. <td>Company Name</td>
44. <td></td>
45. </tr>
46. </table>
47. </td>
48. </tr>
49. </table>
50. </div>
51. </body>
52. </html>

How it works...

What do you think?


I hope you will enjoy the AngularJS scope hierarchy while developing your app with AngularJS. I would
like to have feedback from my blog readers. Your valuable feedback, question, or comments about
this article are always welcome.

Understanding Data Binding in AngularJS


AngularJS data-binding is the most useful feature which saves you from writing boilerplate code (i.e.
the sections of code which is included in many places with little or no alteration). Now, developers are
not responsible for manually manipulating the DOM elements and attributes to reflect model changes.
AngularJS provides two-way data-binding to handle the synchronization of data between model and
view.

How AngularJS handle data binding


AngularJS handle data-binding mechanism with the help of three powerful functions: $watch(),
$digest() and $apply(). Most of the time AngularJS will call the $scope.$watch() and $scope.$digest()
functions for you, but in some cases you may have to call these functions yourself to update new
values.

Two-way data binding


It is used to synchronize the data between model and view. It means, any change in model will update
the view and vice versa. ng-model directive is used for two-way data binding.

Issue with two-way data binding


In order to make data-binding possible, Angular uses $watch APIs to observe model changes on the
scope. Angular registered watchers for each variable on scope to observe the change in its value. If the
value, of variable on scope is changed then the view gets updated automatically.
This automatic change happens because of $digest cycle is triggered. Hence, Angular processes all
registered watchers on the current scope and its children and checks for model changes and calls
dedicated watch listeners until the model is stabilized and no more listeners are fired. Once the $digest
loop finishes the execution, the browser re-renders the DOM and reflects the changes.
By default, every variable on a scope is observed by the angular. In this way, unnecessary variable are
also observed by the angular that is time consuming and as a result page is becoming slow. Hence to
avoid unnecessary observing of variables on scope object, angular introduced one-way data binding.

One-way data binding


This binding is introduced in Angular 1.3. An expression that starts with double colon (::) , is
considered a one-time expression i.e. one-way binding.

Two-Way and One-Way data binding Example


1. <div ng-controller="MyCtrl">
2. <label>Name (two-way binding): <input type="text" ng-model="name" /></label>
3. <strong>Your name (one-way binding):</strong> <br />
4. <strong>Your name (normal binding):</strong>
5. </div>
6. <script>
7. var app = angular.module('app', []);
8. app.controller("MyCtrl", function ($scope) {
9. $scope.name = "Shailendra Chauhan"
10. })
11. </script>

What do you think?


I hope you will enjoy the AngularJS data binding while developing your app with AngularJS. I would
like to have feedback from my blog readers. Your valuable feedback, question, or comments about
this article are always welcome.

Understanding AngularJS scope life-cycle


Scope data goes through a life cycle when the angular app is loaded into the browser. Understanding
the scope life cycle will help you to understand the interaction between scope and other AngularJS
components.
The scope data goes through the following life cycle phases:

1.

Creation

This phase initialized the scope. The root scope is created by the $injector when the application is
bootstrapped. During template linking, some directives create new child scopes.
A digest loop is also created in this phase that interacts with the browser event loop. This digest loop
is responsible to update DOM elements with the changes made to the model as well as executing any
registered watcher functions.

2.

Watcher registration

This phase registers watches for values on the scope that are represented in the template. These
watches propagate model changes automatically to the DOM elements.
You can also register your own watch functions on a scope value by using the $watch() function.

3.

Model mutation

This phase occurs when data in the scope changes. When you make the changes in your angular app
code, the scope function $apply() updates the model and calls the $digest() function to update the
DOM elements and registered watches.
When you do the changes to scope inside your angular code like within controllers or services, angular
internally call $apply() function for you. But when you do the changes to the scope outside the angular
code, you have to call $apply() function explicitly on the scope to force the model and DOM to be
updated correctly.

4.

Mutation observation

This phase occurs when the $digest() function is executed by the digest loop at the end of $apply()
call. When $digest() function executes, it evaluates all watches for model changes. If a value has been
changed, $digest() calls the $watch listener and updates the DOM elements.

5.

Scope destruction

This phase occurs when child scopes are no longer needed and these scopes are removed from the
browsers memory by using $destroy() function. It is the responsibility of the child scope creator to
destroy them via scope.$destroy() API.
This stop propagation of $digest calls into the child scopes and allow the memory to be reclaimed by
the browser garbage collector.

What do you think?


I hope you will enjoy the AngularJS scopes while developing your app with AngularJS. I would like to
have feedback from my blog readers. Your valuable feedback, question, or comments about this article
are always welcome.

Understanding AngularJS digest life-cycle


The digest loop is responsible to update DOM elements with the changes made to the model as well
as executing any registered watcher functions.
The $digest loop is fired when the browser receives an event that can be managed by the angular
context. This loop is made up of two smaller loops. One processes the $evalAsync queue and the other
one processes the $watch list.

The $digest loop keeps iterating until the $evalAsync queue is empty and the $watch list does not
detect any changes in the model. The $evalAsync queue contains those tasks which are scheduled by
$evalAsync() function from a directive or controller.

The $watch list contains watches correspondence to each DOM element which is bound to the $scope
object. These watches are resolved in the $digest loop through a process called dirty checking. The
dirty checking is a process which checks whether a value has changed, if the value has changed, it set
the $scope as dirty. If the $scope is dirty, another $digest loop is triggered.
When you do the changes to the scope outside the angular context, you have to call $apply() function
explicitly on the scope to trigger $digest cycle immediately.

What do you think?


I hope you have goog understanding of angularjs digest life-cycle. I would like to have feedback from
my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Understanding $emit, $broadcast and $on in


AngularJS
AngularJS provides $on, $emit, and $broadcast services for event-based communication between
controllers.

$emit
It dispatches an event name upwards through the scope hierarchy and notify to the registered
$rootScope.Scope listeners. The event life cycle starts at the scope on which $emit was called. The
event traverses upwards toward the root scope and calls all registered listeners along the way. The
event will stop propagating if one of the listeners cancels it.

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Broadcasting</title>
5. <script src="lib/angular.js"></script>
6. <script>
7. var app = angular.module('app', []);
8.
9. app.controller("firstCtrl", function ($scope) {
10. $scope.$on('eventName', function (event, args) {
11. $scope.message = args.message;
12. console.log($scope.message);
13. });
14. });
15.
16. app.controller("secondCtrl", function ($scope) {
17. $scope.handleClick = function (msg) {
18. $scope.$emit('eventName', { message: msg });
19. };
20. });
21.
22. </script>
23. </head>

24. <body ng-app="app">


25. <div ng-controller="firstCtrl" style="border:2px solid #E75D5C; padding:5px;"
>
26. <h1>Parent Controller</h1>
27. <p>Emit Message : </p>
28. <br />
29. <div ng-controller="secondCtrl" style="border:2px solid #428bca;padding:5px;"
>
30. <h1>Child Controller</h1>
31. <input ng-model="msg">
32. <button ng-click="handleClick(msg);">Emit</button>
33. </div>
34. </div>
35. </body>
36. </html>

How it works..

$broadcast
It dispatches an event name downwards to all child scopes (and their children) and notify to the
registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $broadcast was
called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards
toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Broadcasting</title>
5. <script src="lib/angular.js"></script>
6. <script>
7. var app = angular.module('app', []);
8.
9. app.controller("firstCtrl", function ($scope) {

10. $scope.handleClick = function (msg) {


11. $scope.$broadcast('eventName', { message: msg });
12. };
13.
14. });
15.
16. app.controller("secondCtrl", function ($scope) {
17. $scope.$on('eventName', function (event, args) {
18. $scope.message = args.message;
19. console.log($scope.message);
20. });
21. });
22.
23. </script>
24. </head>
25. <body ng-app="app">
26. <div ng-controller="firstCtrl" style="border:2px solid #E75D5C; padding:5px;"
>
27. <h1>Parent Controller</h1>
28. <input ng-model="msg">
29. <button ng-click="handleClick(msg);">Broadcast</button>
30. <br /><br />
31. <div ng-controller="secondCtrl" style="border:2px solid #428bca;padding:5px;"
>
32. <h1>Child Controller</h1>
33. <p>Broadcast Message : </p>
34. </div>
35. </div>
36. </body>
37. </html>

How it works..

$on

It listen on events of a given type. It can catch the event dispatched by $broadcast and $emit.

Note
1. If there is no parent-child relation between your scopes you can inject $rootScope into the controller
and broadcast the event to all child scopes but you cannot emit your event.
2. You can emit your event only when you have parent-child relation and event propagation is initiated
by child. However, $emit can fire an event only for all $rootScope.$on listeners.

What do you think?


I hope you will enjoy the AngularJS event-based communication while developing your app with
AngularJS. I would like to have feedback from my blog readers. Your valuable feedback, question, or
comments about this article are always welcome.

Understanding cookies in AngularJS


AngularJS provides ngCookies module for reading and writing browser cookies. To use it include
the angular-cookies.js file and set ngCookies as a dependency in your angular app. This module
provides two services for cookie management: $cookies and $cookieStore.

$cookies
This service provides read/write access to browser's cookies. If you want to use existing cookie solution,
say read/write cookies from your existing server session system then use $cookie.
1. <script>
2. var app=angular.module('cookiesExample', ['ngCookies']);
3.
4. app.controller('ExampleController', ['$cookies', function ($cookies) {
5. // Retrieving a cookie
6. var favoriteCookie = $cookies.myFavorite;
7. // Setting a cookie
8. $cookies.myFavorite = 'oatmeal';
9. }]);
10. </script>

$cookiesStore
$cookieStore is a thin wrapper around $cookies. It provides a key-value (string-object) storage that is
backed by session cookies. The objects which are put or retrieved from this storage are automatically
serialized or deserialized by angular to JSON and vice versa.
If you are creating a new solution which will persist cookies based on key/value pairs, use $cookieStore.
1. <script>
2. var app=angular.module('cookieStoreExample', ['ngCookies']);
3.

4. app.controller('ExampleController', ['$cookieStore', function ($cookieStore) {


5. // Put cookie
6. $cookieStore.put('myFavorite', 'oatmeal');
7. // Get cookie
8. var favoriteCookie = $cookieStore.get('myFavorite');
9. // Removing a cookie
10. $cookieStore.remove('myFavorite');
11. }]);
12. </script>

What do you think?


I hope you will enjoy the cookies in AngularJS while developing your app with AngularJS. I would like
to have feedback from my blog readers. Your valuable feedback, question, or comments about this
article are always welcome.

Understanding $watch(), $watchgroup() and


$watchCollection() methods of scope
Angular uses $watch APIs to observe model changes on the scope. Angular registered watchers for
each variable on scope to observe the change in its value. If the value, of variable on scope is changed
then the view gets updated automatically. $watch APIs has following methods to observe model
changes on the scope.

$watch
This function is used to observe changes in a variable on the $scope. It accepts three parameters:
expression, listener and equality object, where listener and equality object are optional parameters.
1. $watch(watchExpression, listener, [objectEquality])

Here, watchExpression is the expression in the scope to watch. This expression is called on every
$digest() and returns the value that is being watched.
The listener defines a function that is called when the value of the watchExpression changes to a new
value. If the watchExpression is not changed then listener will not be called.
The objectEquality is a boolean type which is used for comparing the objects for equality using
angular.equals instead of comparing for reference equality.
1.
2.
3.
4.
5.
6.
7.
8.

<script>
scope.name = 'shailendra';
scope.counter = 0;
scope.$watch('name', function (newVal, oldVal) {
scope.counter = scope.counter + 1;
});
</script>

$watchgroup
This function is introduced in Angular1.3. This works the same as $watch() function except that the
first parameter is an array of expressions to watch.
1. $watchGroup(watchExpression, listener)

The listener is passed as an array with the new and old values for the watched variables. The listener
is called whenever any expression in the watchExpressions array changes.
1. <script>
2. $scope.teamScore = 0;
3. $scope.time = 0;
4. $scope.$watchGroup(['teamScore', 'time'], function(newVal, oldVal) {
5. if(newVal[0] > 20){
6. $scope.matchStatus = 'win';
7. }
8. else if (newVal[1] > 60){
9. $scope.matchStatus = 'times up';
10. });
11. </script>

$watchCollection
This function is used to watch the properties of an object and fires whenever any of the properties
change. It takes anobject as the first parameter and watches the properties of the object.
1. $watchCollection(obj, listener)

The listener is called whenever anything within the obj has been changed.
1.
2.
3.
4.
5.
6.
7.
8.

<script>
$scope.names = ['shailendra', 'deepak', 'mohit', 'kapil'];
$scope.dataCount = 4;
$scope.$watchCollection('names', function (newVal, oldVal) {
$scope.dataCount = newVal.length;
});
</script>

What do you think?


I hope you will enjoy the watchers in AngularJS while developing your app with AngularJS. I would like
to have feedback from my blog readers. Your valuable feedback, question, or comments about this
article are always welcome.

Understanding ng-if, ng-switch and ng-repeat


directives
AngularJS provides you ng-if, ng-switch directives to display HTML elements based on conditions or
cases. ng-repeat directive is used to generate HTML from a collection of items.

ng-if
This directive can add / remove HTML elements from the DOM based on an expression. If the
expression is true, it add HTML elements to DOM, otherwise HTML elements are removed from the
DOM.
1. <div ng-controller="MyCtrl">
2. <div ng-if="data.isVisible">ng-if Visible</div>
3. </div>
4.
5. <script>
6. var app = angular.module("app", []);
7. app.controller("MyCtrl", function ($scope) {
8. $scope.data = {};
9. $scope.data.isVisible = true;
10. });
11. </script>

ng-switch
This directive can add / remove HTML elements from the DOM conditionally based on scope
expression.
1. <div ng-controller="MyCtrl">
2. <div ng-switch on="data.case">
3. <div ng-switch-when="1">Shown when case is 1</div>
4. <div ng-switch-when="2">Shown when case is 2</div>
5. <div ng-switch-default>Shown when case is anything else than 1 and 2</div>
6. </div>
7. </div>
8.
9. <script>
10. var app = angular.module("app", []);
11. app.controller("MyCtrl", function ($scope) {
12. $scope.data = {};
13. $scope.data.case = true;
14. });
15. </script>

ng-repeat
This directive is used to iterate over a collection of items and generate HTML from it.

1. <div ng-controller="MyCtrl">
2. <ul>
3. <li ng-repeat="name in names">
4.
5. </li>
6. </ul>
7. </div>
8.
9. <script>
10. var app = angular.module("app", []);
11. app.controller("MyCtrl", function ($scope) {
12. $scope.names = ['Shailendra', 'Deepak', 'Kamal'];
13. });
14. </script>

What do you think?


I hope you will enjoy the ng-if, ng-switch and ng-repeat directives in AngularJS while developing your
app with AngularJS. I would like to have feedback from my blog readers. Your valuable feedback,
question, or comments about this article are always welcome.

Understanding ng-repeat special variables


1.
2.
3.
4.

The ng-repeat directive has a set of special variables which you are useful while iterating the collection.
These variables are as follows:
$index
$first
$middle
$last
The $index contains the index of the element being iterated. The $first, $middle and $last returns a
boolean value depending on whether the current item is the first, middle or last element in the
collection being iterated.
1. <html>
2. <head>
3. <title></title>
4. <script src="lib/angular.js"></script>
5. <script>
6. var app = angular.module("app", []);
7.
8. app.controller("ctrl", function ($scope) {
9. $scope.friends = [{ name: 'shailendra', gender: 'boy' },
10. { name: 'kiran', gender: 'girl' },
11. { name: 'deepak', gender: 'boy' },
12. { name: 'pooja', gender: 'girl' }];
13. });
14. </script>
15. </head>
16. <body ng-app="app">
17. <div ng-controller="ctrl">

18. <ul class="example-animate-container">


19. <li ng-repeat="friend in friends">
20. <div>
21. [1] is a .
22.
23. <span ng-if="$first">
24. <strong>(first element found)</strong>
25. </span>
26. <span ng-if="$middle">
27. <strong>(middle element found)</strong>
28. </span>
29. <span ng-if="$last">
30. <strong>(last element found)</strong>
31. </span>
32. </div>
33. </li>
34. </ul>
35. </div>
36. </body>
37. </html>

How it works..

What do you think?


I hope you will enjoy the ng-repeat directives special variables in AngularJS while developing your app
with AngularJS. I would like to have feedback from my blog readers. Your valuable feedback, question,
or comments about this article are always welcome.

Enabling AngularJS IntelliSense in Visual Studio


2013
Today, AngularJS is most popular JavaScript framework to develop single page application. If you are
using Visual studio as an IDE for developing your app in angularjs, intellisense support for angularjs
help you a lot to develop your application. By default, Visual Studio 2013 doesn't provide better
intellisense support while writing AngularJS code.This article helps you how to enable IntelliSense in
Visual Studio 2013 when working with AngularJS.
If AngularJS is compeletely new to you can learn Step By Step AngularJS from my
blog www.webgeekschool.com

Enabling Angular Intellisense in Visual Studio 2013

First, you need to download the angular.intellisense.js file for Visual Studio and place it in the Program
Files (x86)\Microsoft Visual Studio 12.0\JavaScript\References folder of your machine. Now
open visual studio and have a look on intellisense support as given below:

This support will work the same with any project that uses AngularJS, including Apache Cordova,
ASP.NET MVC, ASP.NET WebForm, LightSwitch, Windows Store apps and any others.

What do you think?


I hope you will enjoy this trick while angularjs programming with Visual Studio. I would like to have
feedback from my blog readers. Your valuable feedback, question, or comments about this article are
always welcome.

CRUD Operations with AngularJS, RequireJS


and WebAPI
AngularJS is most popular MVW Javascript framework for single page application development. Also,
Visual Studio is the best IDE in world to develop your app using JavaScript framework which you love.
This article will demonstrate you how to how use visual studio to develop SPA using AngularJS,
RequireJS and Web API.

Defining AngularJS SPA Folder Structure within VS


There are so many ways to organize your code files in SPA. Here, I have created the folder structure
based on file types. This structure also help me to take the advantage of Visual Studio intellisense. To
enable JavaScript code intellisense just add _references.js file into script folder as shown in given folder
structure.

Setup RequireJS
RequireJS is javascript module and files loader. It help you to manage dependencies and make your
code well organized and structured. It can be downloaded from www.requirejs.org.
1. <!DOCTYPE html>
2. <html xmlns="http://www.w3.org/1999/xhtml">
3. <head>
4. <title>AngularJS SPA</title>
5. <link href="css/bootstrap.css" rel="stylesheet" />
6. <script data-main="scripts/main.js" src="scripts/libs/require.js"></script>
7. </head>
8. <body>
9. <div ng-include="'views/shared/_header.html'"></div>
10. <ui-view></ui-view>
11. </body>
12. </html>

Here, I have added a reference to require.js file and others js files will be loaded by requirejs
asynchronously by using data-main attribute scripts/main.js file. The main.js file is used to define
your application JavaScript modules and files dependencies.
1. require.config({
2. baseurl: '/scripts/',
3. paths: {
4. 'angular': 'libs/angular',
5. 'ngStorage': 'libs/ngStorage',
6. 'ngCookies': 'libs/angular-cookies',
7. 'ui-router': 'libs/angular-ui-router',
8. 'jquery': 'libs/jquery-1.10.2',
9. 'bootstrap': 'libs/bootstrap',
10. 'service': 'services/service',
11. 'homeCtrl': "controllers/homeCtrl",
12. 'accountCtrl': "controllers/accountCtrl",
13. 'filter': "filters/filter",
14. },
15. shim: {
16. ngStorage: {
17. deps: ['angular'],
18. exports: 'angular'
19. },
20. ngCookies: {
21. deps: ['angular'],
22. exports: 'angular'
23. },
24. 'ui-router': {
25. deps: ['angular'],
26. exports: 'angular'
27. },
28. angular: {
29. exports: 'angular'
30. },
31. bootstrap: {
32. deps: ['jquery']
33. }
34. },
35. deps: ['app']
36. });
37.
38. require([
39. "app",
40. "filter",
41. "bootstrap",
42. "homeCtrl",
43. "accountCtrl"
44. ],
45. function (app) {
46. //bootstrapping app
47. app.init();
48. }
49. );

How it works..

Defining AngularJS App Components using RequireJS


To make your javascript code an AMD module just warp your code inside define() method of
requirejs.
define() method takes two arguments - first an optional array of defined module dependencies and
second a callback function. All the modules inside the array will be loaded before this module.

Defining AngularJS Module and Routes (app.js)


1. define(['ui-router', 'ngStorage', 'ngCookies'], function () {
2.
3. //defining angularjs module
4. var app = angular.module("app", ['ui.router', 'ngCookies', 'ngStorage']);
5.
6. //global service
7. app.constant("utility",
8. {
9. baseAddress: "http://localhost:5100/api/"

10. });
11.
12. //manual bootstrap
13. app.init = function () {
14. angular.bootstrap(document, ['app']);
15. };
16.
17. //defining routes
18. app.config(function ($stateProvider, $urlRouterProvider) {
19.
20. $urlRouterProvider.otherwise("/");
21.
22. $stateProvider
23. .state("home", {
24. url: "/",
25. templateUrl: 'views/home/home.html',
26. controller: 'homeCtrl'
27. })
28. .state("about", {
29. url: "/about",
30. templateUrl: 'views/account/about.html',
31. controller: 'aboutCtrl'
32. });
33. });
34. return app;
35. });

Defining AngularJS Service (service.js)


1. define(['app'], function (app) {
2. //defining service using factory method
3. app.factory('userService', function ($http, utility) {
4. var serviceurl = utility.baseAddress + "UserService/";
5. return {
6. getUsersList: function () {
7. var url = serviceurl + "GetUsersList";
8. return $http.get(url);
9. },
10. getUser: function (user) {
11. var url = serviceurl + "GetUser/" + user.UserId;
12. return $http.get(url);
13. },
14. addUser: function (user) {
15. var url = serviceurl + "AddUser";
16. return $http.post(url, user);
17. },
18. deleteUser: function (user) {
19. var url = serviceurl + "DeleteUser/" + user.UserId;
20. return $http.delete(url);
21. },
22. updateUser: function (user) {
23. var url = serviceurl + "ModifyUser/" + user.UserId;
24. return $http.put(url, user);

25. }
26. };
27. });
28. });

Defining AngularJS Controller (homeCtrl.js, accountCtrl.js)


1. //homeCtrl.js
2. define(['app', 'service'], function (app) {
3. app.controller("homeCtrl", function ($scope, userService) {
4. $scope.users = [];
5. $scope.user = null;
6. $scope.editMode = false;
7.
8. //get User
9. $scope.get = function () {
10. $scope.user = this.user;
11. $("#viewModal").modal('show');
12. };
13.
14. // initialize your users data
15. (function () {
16. userService.getUsersList().success(function (data) {
17. $scope.users = data;
18. }).error(function (data) {
19. $scope.error = "An Error has occured while Loading users! " + data.ExceptionM
essage;
20. });
21. })();
22.
23. // add User
24. $scope.add = function () {
25. var currentUser = this.user;
26. if (currentUser != null && currentUser.Name != null && currentUser.Address &&
currentUser.ContactNo) {
27. userService.addUser(currentUser).success(function (data) {
28. $scope.addMode = false;
29. currentUser.UserId = data;
30. $scope.users.push(currentUser);
31.
32. //reset form
33. $scope.user = null;
34. // $scope.adduserform.$setPristine(); //for form reset
35.
36. angular.element('#userModel').modal('hide');
37. }).error(function (data) {
38. $scope.error = "An Error has occured while Adding user! " + data.ExceptionMes
sage;
39. });
40. }
41. };
42.
43. //edit user

44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.

$scope.edit = function () {
$scope.user = this.user;
$scope.editMode = true;
$("#userModel").modal('show');
};
//update user
$scope.update = function () {
var currentUser = this.user;
userService.updateUser(currentUser).success(function (data) {
currentUser.editMode = false;

$('#userModel').modal('hide');
}).error(function (data) {
$scope.error = "An Error has occured while Updating user! " + data.ExceptionM
essage;
60. });
61. };
62.
63. // delete User
64. $scope.delete = function () {
65. currentUser = $scope.user;
66. userService.deleteUser(currentUser).success(function (data) {
67. $('#confirmModal').modal('hide');
68. $scope.users.pop(currentUser);
69.
70. }).error(function (data) {
71. $scope.error = "An Error has occured while Deleting user! " + data.ExceptionM
essage;
72.
73. angular.element('#confirmModal').modal('hide');
74. });
75. };
76.
77. //Model popup events
78. $scope.showadd = function () {
79. $scope.user = null;
80. $scope.editMode = false;
81.
82. $("#userModel").modal('show');
83. };
84.
85. $scope.showedit = function () {
86. $('#userModel').modal('show');
87. };
88.
89. $scope.showconfirm = function (data) {
90. $scope.user = data;
91.
92. $("#confirmModal").modal('show');
93. };
94.
95. $scope.cancel = function () {
96. $scope.user = null;

97. $("#userModel").modal('hide');
98. };
99. });
100. });
1. //accountCtrl.js
2. define(['app'], function (app) {
3. app.controller("aboutCtrl", function ($scope) {
4. $scope.Message = "About Us";
5. });
6. });

Defining Views/Templates
Now defines the view for CRUD operation on user entity. Here, I am using bootstrap modal popups
for Create, Edit and Delete operations.

1. <!-- home.html -->


2. <div class="container">
3. <div ng-app="userApp" class="container">

4.

<div ng-show="error" class="alert alert-danger alert-dismissible" role="alert


">
5. <button type="button" class="close" data-dismiss="alert"><span aria-hidden="t
rue"></span><span class="sr-only">Close</span></button>
6. <p></p>
7. </div>
8.
9. <p><a data-ng-click="showadd()" href="javascript:;" class="btn btn-primary">A
dd New User</a></p>
10.
11. <div class="modal fade" id="userModel" tabindex="-1" role="dialog" aria-hidde
n="true">
12. <div class="modal-dialog">
13. <div class="modal-content">
14. <div class="modal-header">
15. <button type="button" class="close" data-dismiss="modal" aria-hidden="true">X
</button>
16. <h4 class="modal-title" id="myModalLabel" ng-hide="editMode">Add User</h4>
17. <h4 class="modal-title" id="myModalLabel" ng-show="editMode">Edit User</h4>
18. </div>
19. <div class="modal-body">
20. <form class="form-horizontal" role="form" name="adduserform">
21. <div class="form-group">
22. <label for="title" class="col-sm-2 control-label">Name</label>
23. <div class="col-sm-10">
24. <input type="text" data-ng-model="user.Name" class="form-control" id="title" p
laceholder="Your Name" required title="Enter your name" />
25. </div>
26. </div>
27. <div class="form-group">
28. <label for="title" class="col-sm-2 control-label">Address</label>
29. <div class="col-sm-10">
30. <input type="text" data-ng-model="user.Address" class="form-control" id="titl
e" placeholder="Your Address" required title="Enter your address" />
31. </div>
32. </div>
33. <div class="form-group">
34. <label for="title" class="col-sm-2 control-label">ContactNo</label>
35. <div class="col-sm-10">
36. <input type="text" data-ng-model="user.ContactNo" class="form-control" id="ti
tle" placeholder="Your ContactNo" required title="Enter your contactno" />
37. </div>
38. </div>
39. <div class="form-group">
40. <div class="col-sm-offset-2 col-sm-10">
41. <span data-ng-hide="editMode">
42. <input type="submit" value="Add" ng-disabled="adduserform.$invalid" data-ng-c
lick="add()" class="btn btn-primary" />
43. </span>
44. <span data-ng-show="editMode">
45. <input type="submit" value="Update" ng-disabled="adduserform.$invalid" data-n
g-click="update()" class="btn btn-primary" />
46. </span>
47. <input type="button" value="Cancel" data-ng-click="cancel()" class="btn btn-p
rimary" />

48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.

</div>
</div>
</form>
</div>
</div>
</div>
</div>
<h1>Users List</h1>
<table class="table table-hover">
<tr>
<th>User ID</th>
<th>Name</th>
<th>Address</th>
<th>Contact No</th>
<th>Actions</th>
</tr>
<tr data-ng-repeat="user in users">
<td><strong></strong></td>
<td>
<p></p>
</td>
<td>
<p></p>
</td>
<td>
<p></p>
</td>
<td>
<p>
<a data-ng-click="get(user)" href="javascript:;">View</a> |
<a data-ng-click="edit(user)" href="javascript:;">Edit</a> |
<a data-ng-click="showconfirm(user)" href="javascript:;">Delete</a>
</p>
</td>
</tr>
</table>
<hr />

<div class="modal fade" id="viewModal" tabindex="-1" role="dialog" aria-hidde


n="true">
93. <div class="modal-dialog">
94. <div class="modal-content">
95. <div class="modal-header">
96. <button type="button" class="close" data-dismiss="modal" aria-hidden="true">X
</button>
97. <h4 class="modal-title" id="myModalLabel">View User</h4>
98. </div>
99. <div class="modal-body">
100. <form class="form-horizontal" role="form" name="viewuser">

101. <div class="form-group">


102. <label for="Name" class="col-sm-2 control-label">Name</label>
103. <div class="col-sm-10">
104.
105. </div>
106. </div>
107. <div class="form-group">
108. <label for="Address" class="col-sm-2 control-label">Address</label>
109. <div class="col-sm-10">
110.
111. </div>
112. </div>
113. <div class="form-group">
114. <label for="ContactNo" class="col-sm-2 control-label">ContactNo</label>
115. <div class="col-sm-10">
116.
117. </div>
118. </div>
119. </form>
120. </div>
121. <div class="modal-footer">
122. <button type="button" class="btn btn-default" data-dismiss="modal">Close</bu
tton>
123. </div>
124. </div>
125. </div>
126. </div>
127.
128. <div class="modal fade" id="confirmModal" tabindex="-1" role="dialog" aria-h
idden="true">
129. <div class="modal-dialog">
130. <div class="modal-content">
131. <div class="modal-header">
132. <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
X</button>
133. <h4 class="modal-title" id="myModalLabel">Confirm Action</h4>
134. </div>
135. <div class="modal-body">
136. Are you sure to delete?
137. </div>
138. <div class="modal-footer">
139. <button type="button" class="btn btn-default" data-ng-click="delete()">Ok</b
utton>
140. <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</b
utton>
141. </div>
142. </div>
143. </div>
144. </div>
145. </div>
146. </div>

Also, create a view about.html to display information about youself.

1. <!-- about.html -->


2. <div class="container">
3. <div class="col-xs-12 col-sm-12 col-lg-12">
4. <h2></h2>
5. <p>
6. Hey!, I'm an entrepreneur, founder and chief editor of <a href="http://www.do
tnet-tricks.com" class="link">www.dotnet-tricks.com</a> and <a href="http://ww
w.dotnettricks.com" class="link">www.dotnettricks.com</a> - <code>Coding is R
hyme</code>.
7. </p>
8. <p>
9. I have more than 6 years of hand over Microsoft .NET technologies and other w
eb technologies like AngularJS, JavaScript, Hybrid Mobile Apps Development. A n
umber of articles of myself has become <code>articles-of-the-day</code>, selec
ted in <code>daily-community-spotlight</code> and listed in <a href="http://ww
w.asp.net/mvc/overview/getting-started/recommended-resources-for-mvc" class="l
ink" target="_blank">Recommended Resources for MVC</a> section on the Official
<code>Microsoft ASP.NET Community Site.</code>
10. </p>
11. </div>
12. </div>

Creating Data Model and DataContext using Entity


Framework
1. public class User
2. {
3. public int UserId { get; set; }
4.
5. [Required]
6. [MaxLength(50)]
7. [Column(TypeName = "varchar")]
8. public string Name { get; set; }
9.
10. [Required]
11. [MaxLength(200)]
12. [Column(TypeName = "varchar")]
13. public string Address { get; set; }
14.
15. [Column(TypeName = "varchar")]
16. [MaxLength(15)]
17. public string ContactNo { get; set; }
18. }
19.
20. public class DataContext : DbContext
21. {
22. public DataContext():base("DefaultConnection")
23. {
24.
25. }
26.
27. public DbSet User { get; set; }

28. }

Creating REST Service using Web API


1. [EnableCors("*", "*", "*")] //allow cross-origin request
2. public class UserServiceController : ApiController
3. {
4. DataContext context = new DataContext();
5.
6. [HttpPost]
7. public int AddUser(User user)
8. {
9. context.User.Add(user);
10. context.SaveChanges();
11. return user.UserId;
12. }
13.
14. [HttpGet]
15. public User GetUser(int id)
16. {
17. User user = context.User.Find(id);
18. return user;
19. }
20.
21. [HttpGet]
22. public List GetUsersList()
23. {
24. return context.User.ToList();
25. }
26.
27. [HttpPut]
28. public void ModifyUser(User user, int id)
29. {
30. if (user.UserId == id)
31. {
32. context.Entry(user).State = EntityState.Modified;
33. context.SaveChanges();
34. }
35. }
36.
37. [HttpDelete]
38. public void DeleteUser(int id)
39. {
40. User user = context.User.Find(id);
41. if (user != null)
42. {
43. context.User.Remove(user);
44. context.SaveChanges();
45. }
46. }
47. }

How it works..

What do you think?


I hope you will enjoy the article while developing AngularJS SPA using ASP.NET WebAPI and RequireJS.
I would like to have feedback from my blog readers. Your valuable feedback, question, or comments
about this article are always welcome.

Das könnte Ihnen auch gefallen