2. Introduction
AngularJS is an open source, JavaScript based web application
development framework.
It is used in Single Page Application (SPA) projects.
It extends HTML DOM with additional attributes and makes it more
responsive to user actions.
3. The Internet has come a long way since its inception. Consumption-
oriented, non-interactive websites started moving toward something
users interacted with.
Angular is a complete solution, the vast majority of use-cases can be
handled by angular with out using any third party tool or libraries
AngularJS provides developers an options to write client side
applications using JavaScript in a clean Model View Controller (MVC)
way.
Applications written in AngularJS are cross-browser compliant.
AngularJS automatically handles JavaScript code suitable for each
browser.
5. SPA
Single Page Application(SPA) is a web application that fits on a
single web page with dynamic actions without refreshing the
page
Interactions can be handle without reaching server.
It is very easy to navigate to different page and filter content.
There are many tricks and technique can use to build awesome
Single Page Application.
AngularJS is the more popular Single Page Application
framework
6. Core Features
Data-binding
Scope
Controller
Services
Filters
Directives
Templates
Routing
Deep Linking
Dependency Injection
Model View Whatever
7. Advantages of AngularJS
AngularJS provides capability to create Single Page Application in a
very clean and maintainable way.
AngularJS provides data binding capability to HTML. Thus, it gives user
a rich and responsive experience.
AngularJS code is unit testable.
AngularJS uses dependency injection and make use of separation of
concerns.
AngularJS provides reusable components.
With AngularJS, the developers can achieve more functionality with
short code.
In AngularJS, views are pure html pages, and controllers written in
JavaScript do the business processing.
8. On the top of everything, AngularJS applications can run on all major
browsers and smart phones, including Android and iOS based phones/tablets.
9. Disadvantages of AngulaJS
Not Secure : Being JavaScript only framework, application written in
AngularJS are not safe. Server side authentication and authorization is must
to keep an application secure.
Not degradable: If the user of your application disables JavaScript, then
nothing would be visible, except the basic page.
Memory Leak: Memory leak in JavaScript can even cause powerful system to
slow down.
10. MVW
MVC Design Pattern
MVC design pattern is not specific to AngularJS, you must have
seen/implemented this pattern in many other programming languages.
MVC design pattern can be seen in AngularJS
MVC design pattern includes:
1. Model: Model is nothing but data.
2. View: View represents this data.
3. Controller: Controller mediates between the two.
11. In MVC if we make any change in the view it doesn’t gets updated
in model.
But in AngularJS, there is something called 2-way binding and this 2-
way binding enables MVVM design pattern.
MVVM basically includes 3 things:
1. Model
2. View
3. View Model
12.
13. Controller is actually replaced by View Model in MMVM design pattern.
View Model is nothing but a JavaScript function which is again like
a controller and is responsible for maintaining relationship
between view and model, but the difference here is, if we update anything
in view, it gets updated in model, change anything in model, it shows up in
view, which is what we call 2-way binding.
14. In a pure SPA, all UI interaction occurs on the client side, through
JavaScript and CSS. After the initial page load, the server acts purely
as a service layer. The client just needs to know what HTTP requests to
send. It doesn’t care how the server implements things on the back
end.
15. $.getJSON(url)
.done(function (data) {
// On success, "data" contains a list of movies
var ul = $("<ul></ul>")
$.each(data, function (key, item) {
// Add a list item
$('<li>', { text: item.Title }).appendTo(ul);
});
$('#movies').html(ul);
});
16. This code has some problems. It mixes application logic with presentation
logic, and it’s tightly bound to your HTML. Also, it’s tedious to write. Instead
of focusing on your app, you spend your time writing event handlers and
code to manipulate the DOM.
The solution is to build on top of a JavaScript framework. Luckily, you can
choose from many open source JavaScript frameworks. Some of the more
popular ones include Backbone, Angular, Ember, Knockout, Dojo and
JavaScriptMVC.
19. $Scope
Every controller has an associated $scope object.
A controller (constructor) function is responsible for setting model
properties and functions. This can be done only through $scope. Whatever
function or model you apply in View (html file), that is accessed in
controller using scope.
20. Modules
A module is a collection of services, directives, controllers, filters, and
configuration information. angular.module is used to configure the $injector.
However it's more likely that you'll just use ngApp or angular.bootstrap to
simplify this process for you.
The angular.module is a global place for creating, registering and retrieving
Angular modules. All modules (angular core or 3rd party) that should be
available to an application must be registered using this mechanism.
21. Sample code
// Create a new module
var myModule = angular.module('myModule', []);
22. Controller
AngularJS Controllers. The ng-controller directive defines the
application controller. A controller is a JavaScript Object, created by a
standard JavaScript object constructor.
A new child scope will be created and made available as an injectable
parameter to the Controller's constructor function as $scope.
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope',
function($scope) {
$scope.greeting = 'Hola!';
}]);
23. JavaScript coding patterns
JavaScript can be used as a functional language and we can use
functions to create abstractions.
Abstractions are useful because they typically provide some sort of
encapsulation to make other code easier to write.
Angular relies heavily on the functional nature of JavaScript to build
abstractions
24. var work = function( )
{
console.log("do work");
};
work();
var dowork = function(f)
{
console.log("do work started");
f();
console.log("do work ended");
};
dowork(work);
25. Use functions to simulate modules
Functions are a useful abstraction in JavaScript, but sometimes I need
more than just a function. Sometimes I need an object, and that object
has data and it has methods attached to it
var createWorker = function(){
var task1 = function(){ console.log("task1");};
var task2 = function(){ console.log("task2");};
return { job1: task1, job2: task2 };};
var worker = createWorker();
worker.job1();worker.job2();
26. Now what we have achieved is encapsulated some code inside a
function.
Collection of components or features put together to do some work
is called Module.
You can think of a module as a container for the different parts of
your app – controllers, services, filters, directives, etc.
(function(){
//code
})();
27. Define a module
Avoids the global namespace
Angular api – angular.module
One single identifier that angular put into global namespace is
‘anguler’ that we can use anywhere
// .module -> create a module
-> get reference to a module
var app = angular.module(“myModule”, []);
28. Registering controller with module
api - controller
app.controller(“MainController”, MainController)
Map angular with the module
29. Controller
Controllers are one of the central pieces of the Angular framework
With Angular, a controller is in charge or responsible for building a model. A
model contains the data we need to work with and a controller will do
whatever it needs to grab that data.
var MainController = function ($scope)
{
$scope.message = “Hello”;
}
What is attached to $scope, that is going to be the model.
37. The MVC Model vs The Angular Model
In traditional MVC frameworks models are the application’s connection to
the backend data source. When the application is used model’s are
accessed (by the controller) and the retrieved data is blended with the
view template.
38. As the user clicks around, the controller continues to query the
model for data. Once the data is returned it becomes available
to the view at “render” time
AJAX helps with some of this by eliminating the burden of page
reloading just to update potentially small data sets
39. AngularJS takes a different approach to the model
concept
The view and the model are intertwined in an AngularJS
application.
Views are considered a projection of the current model state, as
data sourcing from the view is handled by the model and then
turned around and fed right back into the view.
40. Templates Now it's time to make the web page dynamic — with AngularJS.
In Angular, the view is a projection of the model through the
HTML template.
41. In Angular, templates are written with HTML that contains Angular-
specific elements and attributes.
Angular combines the template with information from the model
and controller to render the dynamic view that a user sees in the
browser.
These are the types of Angular elements and attributes you can use:
Directive — An attribute or element that extends an existing DOM
element or represents a reusable DOM component.
Markup — The double curly brace notation {{ }} to bind expressions to
elements is built-in Angular markup.
Filter — Formats data for display.
Form controls — Validates user input.
42. <html ng-app>
<!-- Body tag augmented with ngController directive -->
<body ng-controller="MyController">
<input ng-model="foo" value="bar">
<!-- Button tag with ng-click directive, and
string expression 'buttonText'
wrapped in "{{ }}" markup -->
<button ng-click="changeFoo()">{{buttonText}}</button>
<script src="angular.js">
</body>
</html>
43. In a more complex app, you can display multiple views within one
main page using "partials" with the help of ngView
Filters
A filter formats the value of an expression for display to the user
> Using filters in view templates - {{ expression | filter }}
Eg: {{ 12 | currency }} -> $12.00.
44. Forms
Controls (input, select, textarea) are ways for a user to enter data.
A Form is a collection of controls for the purpose of grouping related
controls together.
Form and controls provide validation services, so that the user can be
notified of invalid input before submitting a form.
45. Data binding
Data-binding in Angular apps is the automatic synchronization of data
between the model and view components
The way that Angular implements data-binding lets you treat the
model as the single-source-of-truth in your application.
The view is a projection of the model at all times
46. Most templating systems bind data in only one direction:
they merge template and model components together into a view.
After the merge occurs, changes to the model or related sections of the view
are NOT automatically reflected in the view.
Any changes that the user makes to the view are not reflected in the model.
47. Angular templates work differently.
First the template (which is the uncompiled HTML along with any
additional markup or directives) is compiled on the browser.
The compilation step produces a live view. Any changes to the view
are immediately reflected in the model, and any changes in the
model are propagated to the view.
Because the view is just a projection of the model, the controller is
completely separated from the view and unaware of it
48. $scope functions
$watch()
$digest()
$apply()
Understanding $watch(), $digest() and $apply() is
essential in order to understand AngularJS.
49. When you create a data binding to a variable on the $scope
object, AngularJS creates a "watch" internally.
A watch means that AngularJS watches changes in the variable
on the $scope object.
Watches are created using the $scope.$watch() function.
50. The $scope.watch() function creates a watch of some variable. When
you register a watch you pass two functions as parameters to the
$watch() function:
A value function
A listener function
$scope.$watch(function() {},
function() {} );
The first function is the value function and the second function is the
listener function.
The value function should return the value which is being watched.
AngularJS can then check the value returned against the value the
watch function returned the last time. That way AngularJS can
determine if the value has changed. Here is an example:
$scope.$watch(function(scope) { return
scope.data.myVar },
function() {});
51. $digest() function is what triggers the data binding to update.
At key points in our application AngularJS calls the
$scope.$digest() function.
This function iterates through all watches and checks if any of
the watched variables have changed.
If a watched variable has changed, a corresponding listener
function is called.
The listener function does whatever work it needs to do, for
instance changing an HTML text to reflect the new value of the
watched variable.
52. $digest()
The $scope.$digest() function iterates through all the watches
in the $scope object.
When $digest() iterates over the watches, it calls the value
function for each watch. If the value returned by the value
function is different than the value it returned the last time it
was called, the listener function for that watch is called.
The $digest() function is called whenever AngularJS thinks it is
necessary. For instance, after a button click handler has been
executed, or after an AJAX call returns.
53. $apply()
The $scope.$apply() function takes a function as parameter
which is executed, and after that $scope.$digest() is called
internally.
$scope.$apply(function() {
$scope.data.myVar = "Another value";
});
54. <div ng-controller="myController">
{{data.time}}
<br/>
<button ng-click="updateTime()">update time - ng-click</button>
<button id="updateTimeButton" >update time</button>
</div>
<script>
var module = angular.module("myapp", []);
var myController1 = module.controller("myController", function($scope) {
$scope.data = { time : new Date() };
$scope.updateTime = function() {
$scope.data.time = new Date();
}
document.getElementById("updateTimeButton")
.addEventListener('click', function() {
console.log("update time clicked");
$scope.data.time = new Date();
});
});
</script>
$scope.$digest();
$scope.$apply(function() {
console.log("update time clicked");
$scope.data.time = new Date();
});
55. 2- way data binding
The key directive in understanding two-way data-binding is ng-
model. The ng-model directive provides the two-way data-
binding by synchronizing the model to the view, as well as view
to the model.
The direction going from view to model uses standard event
handlers to detect changes that must be updated within the
model.
The direction going from the model back to the view is updated
during a $digest
56. Every element that is on your page that is going to respond to the
digest cycle will, somewhere, attach a listener and an expression to
its scope using $watch.
When you write {{ foo() }}, or when you use ng-model='user.name',
internally there is a call to $watch made on your behalf with a
Javascript expression that will be run every time a digest cycle is
run.
Bindings aren't free, and the more things that are bound, the slower
the page will respond.
One-time bindings are one way of reducing this cost.
Using $on with $emit and $broadcast are another.
57. One-time binding
An expression that starts with :: is considered a one-time expression.
One-time expressions will stop recalculating once they are stable
<div ng-controller="EventController">
<button ng-click="clickMe($event)">Click Me</button>
<p id="one-time-binding-example">One time binding: {{::name}}</p>
<p id="normal-binding-example">Normal binding: {{name}}</p>
</div>
So you will see the changes in the log, because the value actually changes, what will
not change is the view.
58. Expressions
AngularJS expressions are written inside double braces: {{
expression }}.
For example, these are valid expressions in Angular:
1+2
a+b
user.name
items[index]
59. AngularJS expressions binds data to HTML the same way as the ng-
bind directive.
AngularJS will "output" data exactly where the expression is written.
<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div>
The ng-init directive initializes application data.
62. Dependency Injection
Dependency Injection is a software design pattern in which
components are given their dependencies instead of hard
coding them within the component.
This helps in making components reusable, maintainable and
testable.
The Angular injector subsystem is in charge of creating
components, resolving their dependencies, and providing them
to other components as requested.
63. There is one injector per Angular application. Normally you don't need
to interact with it directly. The injector is key to making dependency
injection work in Angular.
Module methods such as factory, service, directive, etc. register these
items with the injector. When you inject something (e.g., a service
into a controller), the injector will lookup and then instantiate the
service (if it wasn't instantiated already -- if it was, it will return the
already-instantiated object).
64. Most applications have a main method that instantiates and wires
together the different parts of the application.
Angular apps don't have a main method. Instead modules declaratively
specify how an application should be bootstrapped. There are several
advantages to this approach:
The declarative process is easier to understand.
You can package code as reusable modules.
The modules can be loaded in any order (or even in parallel) because
modules delay execution.
Unit tests only have to load relevant modules, which keeps them fast.
End-to-end tests can use modules to override configuration.
65. A module is a collection of configuration and run blocks which get
applied to the application during the bootstrap process. In its simplest
form the module consists of a collection of two kinds of blocks:
Configuration blocks - get executed during the provider registrations
and configuration phase. Only providers and constants can be injected
into configuration blocks. This is to prevent accidental instantiation of
services before they have been fully configured.
Run blocks - get executed after the injector is created and are used
to kickstart the application. Only instances and constants can be
injected into run blocks. This is to prevent further system
configuration during application run time.
66. Here's the calling order:
app.config()
app.run()
directive's compile functions (if they are found in the dom)
app.controller()
directive's link functions (again, if found)
67. AngularJS provides a supreme Dependency Injection mechanism. It
provides following core components which can be injected into each
other as dependencies.
value
factory
service
Provider -> Configuration block
Constant -> Configuration block
68. Configuration blocks - get executed during the provider registrations and
configuration phase. Only providers and constants can be injected into
configuration blocks. This is to prevent accidental instantiation of services
before they have been fully configured.
Run blocks - get executed after the injector is created and are used to
kickstart the application. Only instances and constants can be injected into
run blocks. This is to prevent further system configuration during
application run time.
69. angular.module('myModule', []).
config(function(injectables) { // provider-injector
// This is an example of config block.
// You can have as many of these as you want.
// You can only inject Providers (not instances)
// into config blocks.
}).
run(function(injectables) { // instance-injector
// This is an example of a run block.
// You can have as many of these as you want.
// You can only inject instances (not Providers)
// into run blocks
});
70. There are some convenience methods on the module which are equivalent to
the config block.
When bootstrapping, first Angular applies all constant definitions. Then
Angular applies configuration blocks in the same order they were registered.
72. Run Blocks
Run blocks are the closest thing in Angular to the main method. A run block
is the code which needs to run to kickstart the application. It is executed
after all of the services have been configured and the injector has been
created. Run blocks typically contain code which is hard to unit-test, and
for this reason should be declared in isolated modules, so that they can be
ignored in the unit-tests.
73. DI is a pattern which is often used in infrastructure components and which
ensures that one particular component does not directly create references to
other components.
Instead of direct instantiation, every component will receive references to
required other components like helpers, services, etc. as parameters to their
constructor.
Angular's Dependency Injection allows you to write code like the following
without taking into account where $scope comes from.
function UserController($scope) {
$scope.currentUser = {
firstName: "John",
lastName: "Doe"
};
}
74. In this case, $scope gets injected by Angular whenever this controller is
instantiated.
Dependency injection in AngularJS is supremely useful, and the key to
making easily testable components.
Lets have a look how this is happening.
75. The Provider ($provide)
The Injector ($injector)
Controllers ($controller)
Config()
Run()
76. Configuration blocks (registered with module.config()) get executed during
provider registration, and can only be injected providers and constants (see
module.provider() and module.constant()). This is typically where you would
configure application-wide stuff, such as the $routeProvider. Stuff that needs to
be configured before the services are created.
angular.module('crazydeveloperModule', [])
.config(['$httpProvider','$locationProvider','$routeProvider','$provi
der','cookieProvider','constant',
function($httpProvider,
$locationProvider,$routeProvider,$provider,cookieProvider,const ant)
{
// provider-injector This is an example of config block. You can have as
many of these as you want.// You can only inject Providers (not instances) into
config blocks.
}])
77. Run blocks (registered with module.run()) get executed after the injector
has all the providers. Now, all instances and constants can be injected.
This is typically where you would configure services, $rootScope, events
and so on.
angular.module('myModule', [])
. run(['$rootscope','security','pageFactory','$httpBackend',
function ($rootscope,security,pageFactory,$httpBackend) {
// instance-injector
// This is an example of a run block.
// You can have as many of these as you want.
// You can only inject instances (not Providers)
// into run blocks
}]);
78. As you can see in this example, a factory is registered with a module by using
its factory() method. There are additional ways apart from factory() to
configure certain injected values: provider(), constant(), value() and more.
You can find out more about these in Angular's reference - they are all
methods defined on Module (API Reference: angular.Module).
Please note: the return value of a factory method is cached for the complete
execution time of an application. The factory method is therefore called only
once and provides a singleton instance of the requested service.
79. The $provide service is responsible for telling Angular how to create new
injectable things; these things are called services.
Defining a provider is done via the provider method on the $provide service,
and you can get hold of the $provide service by asking for it to be injected into
an application's config function
80. Your first contact with dependency injection is quite likely the $scope
parameter in a controller as shown above. But AngularJS offers more
services than these.
Other base services which you'll encounter are for example:
81.
82. AngularJS injects all parameters whenever a controller is instantiated.
This is performed using Angular's $injector (API Reference:
angular.$injector) which - by default - simply looks at the parameters'
names.
87. Same Old Validation
Here are a few points about what has not changed with validation.
1. When you give a <form> a name, Angular will add a property with the
same name to the current $scope.
2. All named inputs inside a named <form> will be added to the form’s
named property in $scope.
3. Each form and input still have boolean properties to describe if the
object is $pristine or $dirty, and $valid or $invalid.
4. Angular still adds CSS classes to each form and input describing
the state of the object (ng-dirty, ng-pristine, ng-valid, ng-invalid).
5. There is still an $error property on each form and input. The $error
property describes failed validations.
88. ngMessages
Since Angular 1.3, there is a new tool to creating and
managing forms in AngularJS, ngMessages. This module
specifically helps us deal with displaying error messages
from form validation.
89. We are explicitly showing each error message only if that error exists. This can
get tedious when we have multiple errors that we want to show.
This is where ngMessages comes in. This module brings some sanity to validation
messages.
ngMessages is basically looping through the userForm.name.$errors object
and displaying messages based on that.