Beruflich Dokumente
Kultur Dokumente
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
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 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.
<script type="text/javascript">
angular.module('myApp',[]);
angular.module('myApp',['dependentModule1','dependentModule2']);
</script>
1.
2.
3.
4.
5.
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.
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.
<script>
function ProductController($scope){
$scope.Products = [{name: 'Soap', price: 120},
{name: 'Shampoo', price: 100},
{name: 'Hair Oil', price: 60}];
}
</script>
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.
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.
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.
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.
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>
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
1.
$addControl()
Syntax
1. formName.$addControl()
2.
$removeControl()
3.
$setDirty()
4.
$setPristine()
5.
$setValidity()
How it works..
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
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();
}
}
}
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);
}
};
});
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>
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 () {
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.
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.
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>
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);
}
};
});
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>
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.
1.
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 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.
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
$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.
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;})
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(){})
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){});
When to use
When you need to provide module-wise configuration for your service object before making it
available.
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.
//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...
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.
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.
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.
3.
Directive as an element
1. <ng-directive></ng-directive>
4.
Directive as a comment
1. <!-- directive: ng-directive expression -->
Note
Use the data-prefixed version (e.g. data-ng-bind for ngBind ) of directive, if you want to validate
your HTML controls value.
5.
26. });
27. }
28. }
29. }]);
30. </script>
88. </body>
89. </html>
How it works...
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>
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>
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>
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.
http://yourdomain.com/index.html#users
http://yourdomain.com/index.html#orders
http://yourdomain.com/index.html#books
http://yourdomain.com/index.html#games
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.
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>
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>
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>
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.
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()
2.
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>
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...
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.
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.
$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>
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) {
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.
$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.
$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>
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>
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">
How it works..
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.
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..
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. });
25. }
26. };
27. });
28. });
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.
4.
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 />
28. }
How it works..