SlideShare a Scribd company logo
1 of 98
12/21/2015 1
Learning AngularJS
Suresh Patidar
Tailered for 6 day (2hrs/day) sessions
2
Learning Outline
• Day 1
• Introduction
• AngularJS features
• MVC and AngularJS
• Single Page Application (SPA)
• Model, Views, Controllers and Data Binding
• Day 2
• Directives
• Filters
• Localization
• Day 3
• Services
• Routing
• Scopes
3
Learning Outline (cont.)
• Day 4
• Event and Watchers
• Dependency Injection (DI)
• Promises
• Backend Communication
• Day 5
• Angular UI
• Application Organization and module pattern
• Testing
• Day 6
• Common use cases and their answers in AngularJS
• Dependency Management, building and minification
Day 1
5
What is AngularJS?
“A client-side JavaScript Framework for adding interactivity to HTML”
Definition of AngularJS as put by its official documentation is as follows:
AngularJS is a structural framework for dynamic web applications. It lets you use HTML as
your template language and lets you extend HTML's syntax to express your application
components clearly and succinctly. Its data binding and dependency injection eliminate much
of the code you currently have to write. And it all happens within the browser, making it an ideal
partner with any server technology.
It was originally developed in 2009 by Misko Hevery and Adam Abrons. It is now maintained by
Google.
6
Google Trend
7
Core Features
• Data-binding
• It is the automatic synchronization of data between model and view components.
• Scope
• These are objects that refer to the model.
• They act as a glue between controller and view.
• Controller
• These are JavaScript functions bound to a particular scope.
• Services
• AngularJS comes with several built-in services such as $http to make a XMLHttpRequests.
• These are singleton objects which are instantiated only once in app.
• Filters
• These select a subset of items from an array and returns a new array.
8
Core Features (Cont.)
• Directives
• Directives are markers on DOM elements such as elements, attributes, CSS, and more.
• These can be used to create custom HTML tags that serve as new, custom widgets.
• AngularJS has built-in directives such as ngBind, ngModel etc.
• Templates
• These are the rendered view with information from the controller and model.
• These can be a single file (such as index.html) or multiple views in one page using partials.
• Routing
• It is concept of switching views.
9
Core Features (Cont.)
• Model View Whatever
• MVW is a design pattern for dividing an application into different parts called Model, View,
and Controller, each with distinct responsibilities.
• AngularJS does not implement MVC in the traditional sense, but rather something closer to
MVVM (Model-View-ViewModel). The Angular JS team refers it humorously as Model View
Whatever.
• Deep Linking
• Map URL to route definition.
• Deep linking allows you to encode the state of application in the URL so that it can be
bookmarked. The application can then be restored from the URL to the same state.
• Dependency Injection
• AngularJS has a built-in dependency injection subsystem that helps the developer to
create, understand, and test the applications easily.
10
Key Concepts
11
MVC and AngularJS
Model View Controller or MVC as it is popularly called, is a software design pattern for
developing web applications.
A Model View Controller pattern is made up of the following three parts:
• Model
• It is the lowest level of the pattern responsible for maintaining data.
• View
• It is responsible for displaying all or a portion of the data to the user.
• Controller
• It is a software Code that controls the interactions between the Model and View.
12
Single Page Application
Single-Page Applications (SPAs) are Web apps that load a single HTML page and dynamically
update that page as the user interacts with the app.
SPAs use AJAX and HTML5 to create fluid and responsive Web apps, without constant page
reloads. However, this means much of the work happens on the client side, in JavaScript
Challenges with SPA:
• Search Engine Optimization
• Browser history
• Analytics
• Speed of initial load
13
Model, View and Controllers
14
Getting Started
• Environment
• Node JS
• HTTP Server
• npm install -g http-server
• http-server -a localhost -p 8081 -c-1
• JSON Server
• npm install –g json-server
• json-server --port 8989 --watch db.json
15
Basic AngularJS Application
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.17/angular.min.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="HelloController" >
<h2>Welcome {{helloTo.title}} to the world of AngularJS!</h2>
<p> Enter your name: <input type=“text” ng-model=“helloTo.title” /></p>
</div>
<script>
angular.module("myapp", [])
.controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "Guest";
});
</script>
</body>
</html>
Day 2
17
Directive
Directives are one of the most powerful components of AngularJS, helping you extend basic
HTML elements/attributes and create reusable and testable code.
At a high level, directives are markers on a DOM element (such as an attribute, element
name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a
specified behavior to that DOM element (e.g. via event listeners), or even to transform the
DOM element and its children.
18
How does directive works in AngularJS?
When Angular bootstraps your application, the HTML compiler traverses the DOM matching
directives against the DOM elements.
• Matching Directives
• Elements matching “ngModel” directive
• <input type = “text” ng-model = “employee.name” />
• <input type =“text’” data-ng-model = “employee.name” />
• <input type =“text” ng_model = “employee.name” />
• <input type = “text” x:ng:model =“employee.name” />
• Elements matching “enggStudent” directive
• <engg-student></engg-student>
• <div engg-student></div>
• Normalization
• Strip “x-” and “data-” from the front of the element/attribute
• Convert the “:”, “-” or “_” delimited names to camel case
19
AngularJS in-built directives
• ng-app
<div ng-app=“myApp”></div>
• ng-model
<input ng-model = “employee.name” type=“text” />
<h4> Employee Name : {{employee.name}} </h4>
• ng-init
<div ng-init = ‘employee = {name:”admin”}’>Hi, {{employee.name}}</div>
• ng-click
<button ng-click = “count = count + 1”>Click to increment</button>
<h4> Current Count is : {{count}} </h4>
• ng-show/ng-hide
<div ng-show =“isSuperAdmin”>Only for Super Admin </div>
<div ng-hide = “UserNotAuthorized()”>Only for Authorized User</div>
20
AngularJS in-built directives
• ng-repeat
<!-- Iterate through a list of object -- >
<ul>
<li ng-repeat =“employee in employees”>{{employee.name}}</li>
</ul>
<!-- iterate through keys of object
<ul>
<li ng-repeat =“(key,value) in student”>key : {{key}} ; value:{{value}}</li>
</ul>
• ng-src
<img ng-src = “/images/{{id}}.jpg”></img>
• ng-readonly
<input type=“text” ng-model=“employee.name” ng-readonly=“true”></input>
21
AngularJS in-built directives
• ng-if
<div ng-if =“isAuthenticated”>For Authorized users only </div>
<img ng-src = “images/{{id}}.jpg”></img>
• ng-switch
<div ng-switch=“” on=“employee.dept”>
<h2 ng-switch-when = “Admin”> Admin Department</h2>
<h2 ng-switch-when=“Engg”> Engineering Department </h2>
<h2 ng-switch-default> Default Department</h2>
</div>
• ng-include
<div ng-include =“templates/myhtml.htm”></div>
• ng-class
<span ng-class =“{margin:5px;font-size:18px}”>Some Text</span>
22
AngularJS in-built directives
• ng-form
<div ng-form =“userForm”></div>
ng-form properties: $valid, $invalid, $pristine, $dirty, $error
• ng-submit
<form ng-submit=“submitFunction()”></form>
• ng-bind
<span ng-bind=“user.name”></span>
• ng-cloak
<p ng-cloak ng-bind=“user.address”></p>
• ng-controller
<div ng-controller=“myController”></div>
23
Building custom directives
• Directive is powerful tool of AngularJS and should be used carefully
• It is most complicated thing in AngularJS
• Don’t re-invent the wheel, try to use built-in directives
• Design directives by reusing other directives (The modular way of design)
24
Directive Types
$compile can match directives based on element names, attributes, class names, as well
as comments.
So there are essentially four type of directives:
• Element
• <cust-dir></cust-dir>
• Attribute
• <span cust-dir=“exp”></span>
• Class Names
• <span class = “cust-dir:exp;”></span>
• Comment
• <!-- directive:cust-dir exp -->
25
Creating the first Directive
//JS Code
angular.module(“myApp”,[])
.Controller(“myController”,[“$scope”,function($scope){
$scope.employee= {name:”Suresh”,dept:”Engineering”}
}])
.directive(“myEmployee”,function(){
return {
template:”<p>Name:{{employee.name}}</p><p>Department: {{employee.dept}}</p>”
}
});
<!-- HTML Code -->
<div ng-controller=“myController”>
<my-employee></my-employee>
</div>
26
Directive in detail
myApp.directive(“myDirective”,function(){
return {
restrict:’E’ , //E- Element, A- Attribute, C- Class Name; Can have combination like ‘AC’ or ‘AEC’
template:”<div>any html </div>”,
templateUrl:”templatesmytemplate.html”, //Can also be a function(elm,attr) which returns a url
scope: {employeeInfo: ‘=info’}, //Other possible options are &attr (Callback) and @attr (One Way)
link:function(scope, element, attrs, controller, transcludeFuction){
},
transclude:true, //Allow you to access scope outside the directive
require:”^parentCtrl”, //Can be an array if multiple controllers to be passed
controller:[‘$scope’,function($scope){
}],
}
});
27
Filters
Filters allows us to manipulate and filter the presentation of our view.
• Basic Filter
{{totalCost | currency}}
• Chaining filters
{{totalCost | currency | filter1 | filter2}}
• Extending filters with arguments
{{totalCost | currency:”USD$”}}
• Filtering from Controller/JS files
$filter(number)(15,5) //Equivalent to {{15|number:5}}
28
AngularJS built-in filters
• currency
{{totalCost | currency:”$”:4}}
• uppercase
{{name| uppercase}}
• lowercase
{{name| lowercase}}
• number
{{totalCost|number:5}}
• date
{{createdOn | date:’fullDate’}} //Other format “yyyy”, “’Year:’yyyy,’Month:’MMM,’Day:’ EEEE” etc
29
AngularJS built-in filters
• json
{{employeeInfo | json}}
• limitTo
{{userFeedback | limitTo:50}}
• filter
{{ filter_expression | filter : expression : comparator}}
<tr ng-repeat=“employee in employees| filter:searchText:strict">
<td> employee.name</td>
</tr>
• orderBy
{{ orderby_expression | orderBy : expression : reverse}}
<div ng-repeat=“emp in employees| orderBy:”-age”> emp.name</div>
30
Custom filters
Writing your own filter is very easy.
Just register a new filter factory function with your module. Internally, this uses the
filterProvider.
This factory function should return a new filter function which takes the input value as the first
argument.
Any filter arguments are passed in as additional arguments to the filter function.
The filter function should be a pure function, which means that it should be stateless and
idempotent
31
Custom filters
Var myApp = angular.module(‘myApp’, [])
myApp.filter('reverse', function() {
return function(input, uppercase) {
input = input || '';
var out = "";
for (var i = 0; i < input.length; i++) {
out = input.charAt(i) + out;
}
// conditional based on optional argument
if (uppercase) {
out = out.toUpperCase();
}
return out;
};
})
myApp.controller(‘myController', ['$scope',
function($scope) {
$scope.employee = {name:‘Suresh‘, dept:’Engg’};
}
]);
<div ng-controller=“myController">
<input ng-model=“employee.name" type="text"><br>
No filter: {{name}}<br>
Reverse: {{name |reverse}}<br>
Reverse + uppercase: {{name |reverse:true}} <br>
</div>
32
Internationalization & Localization (i18n & l10n)
i18n is a process of developing products in such a way that can be localized for languages and
cultures easily.
l10n is the process of adapting application and text to enable their usability in a particular
culture or linguistic market.
AngularJS provides some functionality for i18n by allowing different pluralization rules through
filters and by allowing users to quickly build custom solutions for string replacement.
For this training we use a popular 3rd party library angular-translate. This library has a great
organization mechanism and easily integrates into an existing AngularJS application. It too has
the ability to interpolate values in strings. It has locale switching, asynchronous loading for
string files, and allows you to translate through directives, filters, and their $translate service. It
also currently has a larger user base and therefore has more guides and questions answered.
33
Internationalization & Localization (i18n & l10n)
• Add reference to file
<script src="path/to/angular-translate.js"></script>
<script src="path/to/angular-translate-loader-static-files.min.js"></script>
• Inject angular-translate module to app as dependency
var app = angular.module('myApp', ['pascalprecht.translate']);
• Configure the Module
app.config(['$translateProvider', function ($translateProvider) {
$translateProvider.useStaticFilesLoader({prefix: 'language/', suffix: '.json'});
$translateProvider.preferredLanguage('en');
$translateProvider.fallbackLanguage('en');
}
])
• Create appropriate resource bundle: “language/en.json”, “language/hi.json”
• Use in HTML : <h1 translate="GREETING_MSG"></h1>
Day 3
35
Services
Angular services are substitutable objects that are wired together using dependency
injection (DI).
You can use services to organize and share code across your app.
Angular services are:
• Lazily instantiated – Angular only instantiates a service when an application component
depends on it.
• Singletons – Each component dependent on a service gets a reference to the single
instance generated by the service factory.
36
Recipe to create services
There are five recipe types that define how to create a Service object.
• Value Recipe
Value service can be used to make some data available across the application
without polluting the global (window) namespace.
var app = angular.module(“myapp”,[]);
app.value(“user”,{name:admin,locale:en,roles:[]});
• Constant Recipe
Constant service can be used to define application level constants. The main
difference between value and constant is that value service can only be injected
into other service or controller while constant can also be injected in module
configuration function.
var app = angular.module(“myapp”,[]);
app.constant(“user”,{SERVER_PREFIX:”api/v2”});
37
Recipe to create services
• Factory Recipe
It allows use other services. When declaring factory name as an injectable
argument we will be provided with the value that is returned by invoking the
function reference passed in module.factory
var app = angular.module(“myapp”,[]);
app.factory(“factoryName”,function(){
return {
sayHello:function(){
return “Hello!”;
}
}
});
38
Recipe to create services
• Service Recipe
When declaring a service name as an injectable argument we will be provided with
an instance of the function reference passed in module.service
var app = angular.module(“myapp”,[]);
app.service(“serviceName”,function(){
this.sayHello = function(){
return “Hello!”;
}
});
39
Recipe to create services
• Provider Recipe
When declaring a provider name as an injectable argument we will be provided with
an object returned by $get call on new instance of the function reference passed in
module.provider. Provider has advantage that they can be configured during module
configuration phase.
var app = angular.module(“myapp”,[]);
app.provider(“providerName”,function(){
this.name = “Guest”;
this.$get = function(){
var name = this.name;
return {
sayHello:function(){return “Hello “ + name};
}
};
this.setName = function(name){this.name = name};
});
40
Let’s use all of them
var app = angular.module(“myapp”,[]);
//User provider type service in config
app.config([“providerName”,function(providerName){
providerName.setName(“Suresh”);
}]);
//Use all types in controller
app.controller([“$scope”,”providerName”,”factoryName”,”serviceName”,
function($scope, providerName, factoryName, serviceName){
$scope.helloList = [ providerName.sayHello(),
factoryName.sayHello(),
serviceName.sayHello()
];
}]);
41
Routing and multiple views
Routing is the most important feature of AngularJS framework which helps us developing Rich
Interactive Applications (RIA). It enables partial page update by just changing a section of page.
AngularJS provides a different module (Not part of core framework) which take case of routing.
Steps for working with Routing:
• Add reference to angular-route in your html file.
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
• Inject ngRoute in your application module.
var myApp = angular.module('myApp', ['ngRoute']);
42
Routing and multiple views
• Configure your application for different routes
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
// route for the about page
.when('/', {
templateUrl : 'templates/home.html',
controller : 'mainController'
})
// Add other routes as required
//Add default route
.otherwise({ redirectTo: '/' });
}]);
43
Scopes
Scope is an object that refers to the application model. It is an execution context for
expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of
the application. Scopes can watch expressions and propagate events.
Scope is the glue between application controller and the view. During the template linking
phase the directives set up $watch expressions on the scope. The $watch allows the directives
to be notified of property changes, which allows the directive to render the updated value to the
DOM.
Each Angular application has exactly one root scope, but may have several child scopes.
Scopes can propagate events in similar fashion to DOM events. The event can be broadcasted
to the scope children or emitted to scope parents.
44
Scope lifecycle
• Creation
The root scope is created during the application bootstrap by the $injector. During
template linking, some directives create new child scopes
• Watcher registration
During template linking directives register watches on the scope. These watches will be
used to propagate model values to the DOM.
• Model Mutation
For mutations to be properly observed, you should make them only within the
scope.$apply().
• Mutation observation
At the end of $apply, Angular performs a $digest cycle on the root scope, which then
propagates throughout all child scopes.
• Scope destruction
When child scopes are no longer needed, it is the responsibility of the child scope creator
to destroy them via scope.$destroy() API
Day 4
46
Event and Watchers
Events and watchers are the great way to implement loose coupling in your application
architecture. AngularJS has good support for publish/subscribe design pattern, in fact the
whole AngularJS framework is based on this design pattern only.
Fire Events:
• $emit(name, args)
Dispatches an event name upwards through the scope hierarchy notifying the
registered listeners.
The event life cycle starts at the scope on which $emit was called. All listeners listening
for name event on this scope get notified. Afterwards, 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.
47
Event and Watchers
• $broadcast(name, args)
Dispatches an event name downwards to all child scopes (and their children) notifying
the registered listeners.
The event life cycle starts at the scope on which $broadcast was called. All listeners
listening for name event on this scope get notified. Afterwards, the event propagates
to all direct and indirect scopes of the current scope and calls all registered listeners
along the way. The event cannot be canceled.
Listen on Events:
• $on(name, listener)
Listens on events of a given type.
The event listener function format is: function(event, args...)
The event object passed into the listener has multiple attribute like targetScope,
currentScope, name, stopPropogation etc.
48
Event and Watchers
Watch for changes:
• $watch(watchExpression, listener, [objectEquality])
Watch Expression should be idempotent i.e. It should not change its value when
called multiple times.
The listener is called only when the value from the current watchExpression and the
previous call to watchExpression are not equal.
Inequality is determined according to reference inequality, strict comparison via the
!== Javascript operator, unless objectEquality == true
• $watchGroup(watchExpressions, listener)
A variant of $watch() where it watches an array of watchExpressions. If any one
expression in the collection changes the listener is executed.
• $watchCollection(obj, listener);
Shallow watches the properties of an object and fires whenever any of the properties
change (for arrays, this implies watching the array items; for object maps, this implies
watching the properties)
49
Performance optimization while using events
50
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.
AngularJS provides a supreme Dependency Injection mechanism. It provides its core
components (services created using different recipes) which can be injected into each other
as dependencies.
Let’s have a look at some examples of DI:
someModule.controller('MyController', ['$scope', 'greeter', function($scope, greeter) {
// ...
}]);
var MyController = function($scope, greeter) {
// ...
}
MyController.$inject = ['$scope', 'greeter'];
51
Promises
A promise represents the eventual result of an operation. You can use a promise to specify
what to do when an operation eventually succeeds or fails.
Promises in AngularJS are provided by the built-in $q service. They provide a way to execute
asynchronous functions in series by registering them with a promise object.
• Deferred Object
• A deferred object is simply an object that exposes a promise as well as the
associated methods for resolving that promise.
• It is constructed using the $q.defer () function and exposes three main methods:
resolve(), reject(), and notify().
• The associated promise object can be accessed via the promise property.
52
Promises
• Promise Object
• We can obtain a Promise object by accessing promise property of deferred object
(defer.promise).
• We can register a callback function on the promise object that'll be executed after the
async function completes.
• Fulfill the Promise
• We can call reslolve() method of deferred object (defer.reslve())to fulfill the promise.
• Rejecting a Promise
• We can call reject() method of deferred object [defer.reject(data)] to reject the promise
in case of something goes wrong.
• Resolving multiple promises
• $q.all(promiseArray) returns a promise that is resolved when all of the promises in the
specified array are resolved or any of them is rejected
53
Promises
• Finally method
• One of the guarantees promises make is that either the success or the error callback will
be invoked, but never both. What happens if you need to ensure a specific function
executes regardless of the result of the promise? You can do this by registering that
function on the promise using the finally() method.
• Promise chaining
• One of the most powerful features of promises is the ability to chain them together. This
allows the data to flow through the chain and be manipulated and mutated at each step.
$http.get(‘someUrl’)
.then(function(resp){
return $http.get(‘otherUrl’);
})
.then(function(resp){
})
.catch(function(error){
});
54
Advanced Promises - Routing
var getName = function(NameService) {
return NameService.getName();
};
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'MainController'
})
.when('/profile', {
templateUrl: 'profile.html',
controller: 'ProfileController‘,
/* only navigate when we've resolved these promises */
resolve: { name: getName}
})
55
Backend Communication
Angular provides a rich built in support for communication with the server, it not only provides
the low level mechanism which acts as building block to communicate with the servers, but it
also provides built-in wrappers for communication with RESTful services
• Communicating with $http
The $http service is a core Angular service that facilitates communication with the remote
HTTP servers via the browser's XMLHttpRequest object or via JSONP
This service provides basic functionalities like:
• GET
• POST HEAD
• DELETE
• PUT
• JSONP
56
Backend Communication
• $http supported options
$http({
method: string, // GET, POST, PUT, HEAD etc
url: string, // URL of resource being requested
params: object, // Query parameters, if not string goes as JSON string
data: string or object, // Data to be sent as request message data
headers: object, // Map representing the HTTP header
transformRequest: function transform(data, headersGetter) or an array of functions, // Transforms request
transformResponse: function transform(data, headersGetter) or an array of functions, // Transforms
response
cache: boolean or Cache object, // Boolean to turn cache on or off
timeout: number, // Timeout to wait for response from server
withCredentials: boolean
});
57
Backend Communication
• Communicating with RESTful Services using $resource
Angular provides built in support to create a service using $resource object.
This object provides common functionalities out of the box, without even writing a
single line like Get, Save, Query, Remove, Delete
$resource is an optional module in Angular defined in a separate file, so we have to
include its JS file in our HTML file.
<script src=” angular-resource.js”></script>
The $resource service accepts 1 required parameter and 2 optional parameters:
• URL required: The URL where the resource is available
• Query params: Parameters to be passed with URL
• Additional functions: Additional methods we want to add to the service.
Day 5
59
AngularUI
Angular UI is project that includes UI modules developed to used in AngularJS Applications.
It includes UI-bootstrap that is Bootstrap UI elements for AngularJS.
It also includes many other Angular variants of famous JQuery UI modules.
AngularUI is an organization that originally started off as one project to consolidate efforts
people were making early on across the entire community to create defacto widgets and
directives for AngularJS (like jQueryUI is to jQuery).
Although it started off as one project with multiple widget wrappers, it's evolved into an
organization with multiple teams and projects with different focuses.
60
AngularUI – UI Bootstrap
• It is a set of native AngularJS directives based on Bootstrap’s markup and CSS.
• The only dependency for this is AngularJS lib file and Bootstrap CSS file.
• Installation
• Download the library file from github repo (https://github.com/angular-
ui/bootstrap/tree/gh-pages) and include in index.html file.
• Download the bootstrap css lib file and include in head section of your index.html
• Define the dependency in your module
• angular.module('myModule', ['ui.bootstrap']);
• Find a detailed list of features with demo refer to below link
• http://angular-ui.github.io/bootstrap/
61
AngularJS module pattern
• In AngularJS world EVERYTHING is a module.
• AngularJS modules can be defined in any order, including dependency modules that
haven’t been defined yet.
Module Pattern in JavaScript (self executing functions):
• Variable scope encapsulation.
• Imports any dependency through functions parameters.
• Exports its own functionality as a return statement.
var MyModule = ( function( dependency ) {
var _otherModuleVar = dependency || {};
var _privateMethod = function(){/* Function logic goes here */ };
return {
publicMethod:function(){ _privateMethod() }
};
})(otherModule);
62
AngularJS module pattern
63
AngularJS application organization
Standard Structure
64
AngularJS application organization
A Better Structure for large application
65
Reorganize our Sample Application
Create a directory structure and move the files at their proper place
66
Reorganize our Sample Application
home.js
67
Reorganize our Sample Application
about.js
68
Reorganize our Sample Application
app.js
69
Reorganize our Sample Application
index.html
70
Testing
AngularJS has very good support of testing as it is written with testability in mind.
• Environment Setup
• Karma (Test Runner)
• Jasmine
• Protractor (End to End test Runner)
71
Node Package file
72
Karma Config file
73
Writing Unit Test:- Check if controller injected
74
Writing Unit Test:- Testing Directive
75
Run Unit Test
• Execute command “npm test”
76
End to End Testing- Protractor config
77
End to End Testing- Write Scenarios
78
Run End to End
• Execute command “npm run protractor”
Day 6
80
Common Use Cases
Sharing Models Between Nested Controllers
Use JavaScript objects instead of primitives or direct $parent scope references.
81
Common Use Cases
Sharing Code Between Controllers using Services
Utilize a Service to implement your business logic and use dependency injection to use this
service in your controllers.
82
Common Use Cases
Changing the DOM in Response to User Actions
Implement a directive my-widget that contains an example paragraph of text we want to style.
83
Common Use Cases
Passing Configuration Parameters Using HTML Attributes
Use the attribute-based directive and pass an attribute value for the configuration. The attribute
is passed as a parameter to the link function.
84
Common Use Cases
Directive-to-Directive Communication
We implement a directive basket with a controller function and two other directive orange and
apple which “require” this controller
85
Common Use Cases
Using Route Location to Implement a Navigation Menu
Use the $location service in a controller to compare the address bar URL to the navigation
menu item the user selected.
86
Common Use Cases
Listening on Route Changes to Implement a Login Mechanism
Implement a listener on the $routeChangeStart event to track the next route navigation.
Redirect to a login page if the user is not yet logged in.
87
Common Use Cases
Editing Text In-Place using HTML5 ContentEditable
Implement a directive for the contenteditable attribute and use ng-model for data binding.
88
Common Use Cases
Displaying a Modal Dialog
Use the angular-ui module’s nice modal plugin, which directly supports Twitter Bootstrap.
89
Common Use Cases
Displaying a Loading Spinner
An Angular.js interceptor for all AJAX calls can be used, which allows you to execute code
before the actual request is started and when it is finished.
90
Dependency Management
• Dependency Management
• Bower
• Install bower by from command prompt “npm install bower -g”
• Install dependency by command “bower install”
bower.json
.bowerrc
91
Building and Minification
• Building and Minification
• Grunt
• npm install grunt-ts –save
• npm install grunt-cli –g
Define the required packages as devDependency in package.json and Run “npm install”
92
Creating gruntfile.js
93
Creating gruntfile.js
94
Creating gruntfile.js
95
Making changes in Index.html
96
Building using Grunt
• Building
• Run “grunt” command
• It will execute default task defined in gruntfile.js
• We defined “grunt.registerTask('default', ['uglify','string-replace']);” so minification
and string replace task will be executed.
97
What’s Next !!!
The next version of AngularJS, “Angular” is already released
which includes lot of improvement and learnings from
AngularJS framework.
Soon, we will have learning sessions on Angular as well.
 HAPPY LEARNING 
98
Thank You !!!

More Related Content

What's hot

Asp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin SawantAsp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin SawantNitin Sawant
 
Angular JS tutorial
Angular JS tutorialAngular JS tutorial
Angular JS tutorialcncwebworld
 
Angular JS, A dive to concepts
Angular JS, A dive to conceptsAngular JS, A dive to concepts
Angular JS, A dive to conceptsAbhishek Sur
 
ASP .NET MVC
ASP .NET MVC ASP .NET MVC
ASP .NET MVC eldorina
 
React js, node js &amp; angular js which one is the best for web development
React js, node js &amp; angular js  which one is the best for web development React js, node js &amp; angular js  which one is the best for web development
React js, node js &amp; angular js which one is the best for web development Concetto Labs
 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarAppfinz Technologies
 
Angular Project Report
 Angular Project Report Angular Project Report
Angular Project ReportKodexhub
 
Introducing Pebble SDK 2.0
Introducing Pebble SDK 2.0Introducing Pebble SDK 2.0
Introducing Pebble SDK 2.0Cherie Williams
 
ASP .NET MVC Introduction & Guidelines
ASP .NET MVC Introduction & Guidelines  ASP .NET MVC Introduction & Guidelines
ASP .NET MVC Introduction & Guidelines Dev Raj Gautam
 
Angular View Encapsulation
Angular View EncapsulationAngular View Encapsulation
Angular View EncapsulationJennifer Estrada
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAERon Reiter
 
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSSoftware architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSJinkyu Kim
 
Developing dynamic ui using react
Developing dynamic ui using reactDeveloping dynamic ui using react
Developing dynamic ui using reactsushmita bhor
 

What's hot (20)

Asp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin SawantAsp.net mvc presentation by Nitin Sawant
Asp.net mvc presentation by Nitin Sawant
 
ASP .net MVC
ASP .net MVCASP .net MVC
ASP .net MVC
 
AngularJS
AngularJSAngularJS
AngularJS
 
Angular JS tutorial
Angular JS tutorialAngular JS tutorial
Angular JS tutorial
 
Angular JS, A dive to concepts
Angular JS, A dive to conceptsAngular JS, A dive to concepts
Angular JS, A dive to concepts
 
ASP .NET MVC
ASP .NET MVC ASP .NET MVC
ASP .NET MVC
 
React js, node js &amp; angular js which one is the best for web development
React js, node js &amp; angular js  which one is the best for web development React js, node js &amp; angular js  which one is the best for web development
React js, node js &amp; angular js which one is the best for web development
 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumar
 
Angular Project Report
 Angular Project Report Angular Project Report
Angular Project Report
 
What's new in Angular 2?
What's new in Angular 2?What's new in Angular 2?
What's new in Angular 2?
 
JavaScript MVC Frameworks: Backbone, Ember and Angular JS
JavaScript MVC Frameworks: Backbone, Ember and Angular JSJavaScript MVC Frameworks: Backbone, Ember and Angular JS
JavaScript MVC Frameworks: Backbone, Ember and Angular JS
 
Introducing Pebble SDK 2.0
Introducing Pebble SDK 2.0Introducing Pebble SDK 2.0
Introducing Pebble SDK 2.0
 
ASP .NET MVC Introduction & Guidelines
ASP .NET MVC Introduction & Guidelines  ASP .NET MVC Introduction & Guidelines
ASP .NET MVC Introduction & Guidelines
 
Angular View Encapsulation
Angular View EncapsulationAngular View Encapsulation
Angular View Encapsulation
 
AngularJS is awesome
AngularJS is awesomeAngularJS is awesome
AngularJS is awesome
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSSoftware architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
Developing dynamic ui using react
Developing dynamic ui using reactDeveloping dynamic ui using react
Developing dynamic ui using react
 
Getting started with angular js
Getting started with angular jsGetting started with angular js
Getting started with angular js
 

Similar to Learning AngularJS - Complete coverage of AngularJS features and concepts

Similar to Learning AngularJS - Complete coverage of AngularJS features and concepts (20)

AngularJS
AngularJSAngularJS
AngularJS
 
AngularJS By Vipin
AngularJS By VipinAngularJS By Vipin
AngularJS By Vipin
 
Angular JS Indtrodution
Angular JS IndtrodutionAngular JS Indtrodution
Angular JS Indtrodution
 
AngularJS
AngularJSAngularJS
AngularJS
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Angular js
Angular jsAngular js
Angular js
 
Angular js
Angular jsAngular js
Angular js
 
Intoduction to Angularjs
Intoduction to AngularjsIntoduction to Angularjs
Intoduction to Angularjs
 
Module2
Module2Module2
Module2
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
 
AngularJs Basic Concept
AngularJs Basic ConceptAngularJs Basic Concept
AngularJs Basic Concept
 
Wt unit 5 client &amp; server side framework
Wt unit 5 client &amp; server side frameworkWt unit 5 client &amp; server side framework
Wt unit 5 client &amp; server side framework
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Angular patterns
Angular patternsAngular patterns
Angular patterns
 
Angularjs
AngularjsAngularjs
Angularjs
 
Introduction to AngularJS By Bharat Makwana
Introduction to AngularJS By Bharat MakwanaIntroduction to AngularJS By Bharat Makwana
Introduction to AngularJS By Bharat Makwana
 
Angular js for Beginnners
Angular js for BeginnnersAngular js for Beginnners
Angular js for Beginnners
 
Angular JS - Introduction
Angular JS - IntroductionAngular JS - Introduction
Angular JS - Introduction
 
Angularjs for kolkata drupal meetup
Angularjs for kolkata drupal meetupAngularjs for kolkata drupal meetup
Angularjs for kolkata drupal meetup
 
Angular js
Angular jsAngular js
Angular js
 

More from Suresh Patidar

Conducting Effective Interviews
Conducting Effective InterviewsConducting Effective Interviews
Conducting Effective InterviewsSuresh Patidar
 
Conducting Good Interviews
Conducting Good InterviewsConducting Good Interviews
Conducting Good InterviewsSuresh Patidar
 
Web worker in your angular application
Web worker in your angular applicationWeb worker in your angular application
Web worker in your angular applicationSuresh Patidar
 
Developing high performance and responsive web apps using web worker
Developing high performance and responsive web apps using web workerDeveloping high performance and responsive web apps using web worker
Developing high performance and responsive web apps using web workerSuresh Patidar
 
Introduction to Modern and Emerging Web Technologies
Introduction to Modern and Emerging Web TechnologiesIntroduction to Modern and Emerging Web Technologies
Introduction to Modern and Emerging Web TechnologiesSuresh Patidar
 
Building Modern Web Apps with MEAN Stack
Building Modern Web Apps with MEAN StackBuilding Modern Web Apps with MEAN Stack
Building Modern Web Apps with MEAN StackSuresh Patidar
 
Space-Based Architecture
Space-Based ArchitectureSpace-Based Architecture
Space-Based ArchitectureSuresh Patidar
 
Modern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web DevelopmentModern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web DevelopmentSuresh Patidar
 

More from Suresh Patidar (8)

Conducting Effective Interviews
Conducting Effective InterviewsConducting Effective Interviews
Conducting Effective Interviews
 
Conducting Good Interviews
Conducting Good InterviewsConducting Good Interviews
Conducting Good Interviews
 
Web worker in your angular application
Web worker in your angular applicationWeb worker in your angular application
Web worker in your angular application
 
Developing high performance and responsive web apps using web worker
Developing high performance and responsive web apps using web workerDeveloping high performance and responsive web apps using web worker
Developing high performance and responsive web apps using web worker
 
Introduction to Modern and Emerging Web Technologies
Introduction to Modern and Emerging Web TechnologiesIntroduction to Modern and Emerging Web Technologies
Introduction to Modern and Emerging Web Technologies
 
Building Modern Web Apps with MEAN Stack
Building Modern Web Apps with MEAN StackBuilding Modern Web Apps with MEAN Stack
Building Modern Web Apps with MEAN Stack
 
Space-Based Architecture
Space-Based ArchitectureSpace-Based Architecture
Space-Based Architecture
 
Modern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web DevelopmentModern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web Development
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 

Recently uploaded (20)

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 

Learning AngularJS - Complete coverage of AngularJS features and concepts

  • 1. 12/21/2015 1 Learning AngularJS Suresh Patidar Tailered for 6 day (2hrs/day) sessions
  • 2. 2 Learning Outline • Day 1 • Introduction • AngularJS features • MVC and AngularJS • Single Page Application (SPA) • Model, Views, Controllers and Data Binding • Day 2 • Directives • Filters • Localization • Day 3 • Services • Routing • Scopes
  • 3. 3 Learning Outline (cont.) • Day 4 • Event and Watchers • Dependency Injection (DI) • Promises • Backend Communication • Day 5 • Angular UI • Application Organization and module pattern • Testing • Day 6 • Common use cases and their answers in AngularJS • Dependency Management, building and minification
  • 5. 5 What is AngularJS? “A client-side JavaScript Framework for adding interactivity to HTML” Definition of AngularJS as put by its official documentation is as follows: AngularJS is a structural framework for dynamic web applications. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application components clearly and succinctly. Its data binding and dependency injection eliminate much of the code you currently have to write. And it all happens within the browser, making it an ideal partner with any server technology. It was originally developed in 2009 by Misko Hevery and Adam Abrons. It is now maintained by Google.
  • 7. 7 Core Features • Data-binding • It is the automatic synchronization of data between model and view components. • Scope • These are objects that refer to the model. • They act as a glue between controller and view. • Controller • These are JavaScript functions bound to a particular scope. • Services • AngularJS comes with several built-in services such as $http to make a XMLHttpRequests. • These are singleton objects which are instantiated only once in app. • Filters • These select a subset of items from an array and returns a new array.
  • 8. 8 Core Features (Cont.) • Directives • Directives are markers on DOM elements such as elements, attributes, CSS, and more. • These can be used to create custom HTML tags that serve as new, custom widgets. • AngularJS has built-in directives such as ngBind, ngModel etc. • Templates • These are the rendered view with information from the controller and model. • These can be a single file (such as index.html) or multiple views in one page using partials. • Routing • It is concept of switching views.
  • 9. 9 Core Features (Cont.) • Model View Whatever • MVW is a design pattern for dividing an application into different parts called Model, View, and Controller, each with distinct responsibilities. • AngularJS does not implement MVC in the traditional sense, but rather something closer to MVVM (Model-View-ViewModel). The Angular JS team refers it humorously as Model View Whatever. • Deep Linking • Map URL to route definition. • Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state. • Dependency Injection • AngularJS has a built-in dependency injection subsystem that helps the developer to create, understand, and test the applications easily.
  • 11. 11 MVC and AngularJS Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three parts: • Model • It is the lowest level of the pattern responsible for maintaining data. • View • It is responsible for displaying all or a portion of the data to the user. • Controller • It is a software Code that controls the interactions between the Model and View.
  • 12. 12 Single Page Application Single-Page Applications (SPAs) are Web apps that load a single HTML page and dynamically update that page as the user interacts with the app. SPAs use AJAX and HTML5 to create fluid and responsive Web apps, without constant page reloads. However, this means much of the work happens on the client side, in JavaScript Challenges with SPA: • Search Engine Optimization • Browser history • Analytics • Speed of initial load
  • 13. 13 Model, View and Controllers
  • 14. 14 Getting Started • Environment • Node JS • HTTP Server • npm install -g http-server • http-server -a localhost -p 8081 -c-1 • JSON Server • npm install –g json-server • json-server --port 8989 --watch db.json
  • 15. 15 Basic AngularJS Application <!doctype html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.17/angular.min.js"></script> </head> <body ng-app="myapp"> <div ng-controller="HelloController" > <h2>Welcome {{helloTo.title}} to the world of AngularJS!</h2> <p> Enter your name: <input type=“text” ng-model=“helloTo.title” /></p> </div> <script> angular.module("myapp", []) .controller("HelloController", function($scope) { $scope.helloTo = {}; $scope.helloTo.title = "Guest"; }); </script> </body> </html>
  • 16. Day 2
  • 17. 17 Directive Directives are one of the most powerful components of AngularJS, helping you extend basic HTML elements/attributes and create reusable and testable code. At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.
  • 18. 18 How does directive works in AngularJS? When Angular bootstraps your application, the HTML compiler traverses the DOM matching directives against the DOM elements. • Matching Directives • Elements matching “ngModel” directive • <input type = “text” ng-model = “employee.name” /> • <input type =“text’” data-ng-model = “employee.name” /> • <input type =“text” ng_model = “employee.name” /> • <input type = “text” x:ng:model =“employee.name” /> • Elements matching “enggStudent” directive • <engg-student></engg-student> • <div engg-student></div> • Normalization • Strip “x-” and “data-” from the front of the element/attribute • Convert the “:”, “-” or “_” delimited names to camel case
  • 19. 19 AngularJS in-built directives • ng-app <div ng-app=“myApp”></div> • ng-model <input ng-model = “employee.name” type=“text” /> <h4> Employee Name : {{employee.name}} </h4> • ng-init <div ng-init = ‘employee = {name:”admin”}’>Hi, {{employee.name}}</div> • ng-click <button ng-click = “count = count + 1”>Click to increment</button> <h4> Current Count is : {{count}} </h4> • ng-show/ng-hide <div ng-show =“isSuperAdmin”>Only for Super Admin </div> <div ng-hide = “UserNotAuthorized()”>Only for Authorized User</div>
  • 20. 20 AngularJS in-built directives • ng-repeat <!-- Iterate through a list of object -- > <ul> <li ng-repeat =“employee in employees”>{{employee.name}}</li> </ul> <!-- iterate through keys of object <ul> <li ng-repeat =“(key,value) in student”>key : {{key}} ; value:{{value}}</li> </ul> • ng-src <img ng-src = “/images/{{id}}.jpg”></img> • ng-readonly <input type=“text” ng-model=“employee.name” ng-readonly=“true”></input>
  • 21. 21 AngularJS in-built directives • ng-if <div ng-if =“isAuthenticated”>For Authorized users only </div> <img ng-src = “images/{{id}}.jpg”></img> • ng-switch <div ng-switch=“” on=“employee.dept”> <h2 ng-switch-when = “Admin”> Admin Department</h2> <h2 ng-switch-when=“Engg”> Engineering Department </h2> <h2 ng-switch-default> Default Department</h2> </div> • ng-include <div ng-include =“templates/myhtml.htm”></div> • ng-class <span ng-class =“{margin:5px;font-size:18px}”>Some Text</span>
  • 22. 22 AngularJS in-built directives • ng-form <div ng-form =“userForm”></div> ng-form properties: $valid, $invalid, $pristine, $dirty, $error • ng-submit <form ng-submit=“submitFunction()”></form> • ng-bind <span ng-bind=“user.name”></span> • ng-cloak <p ng-cloak ng-bind=“user.address”></p> • ng-controller <div ng-controller=“myController”></div>
  • 23. 23 Building custom directives • Directive is powerful tool of AngularJS and should be used carefully • It is most complicated thing in AngularJS • Don’t re-invent the wheel, try to use built-in directives • Design directives by reusing other directives (The modular way of design)
  • 24. 24 Directive Types $compile can match directives based on element names, attributes, class names, as well as comments. So there are essentially four type of directives: • Element • <cust-dir></cust-dir> • Attribute • <span cust-dir=“exp”></span> • Class Names • <span class = “cust-dir:exp;”></span> • Comment • <!-- directive:cust-dir exp -->
  • 25. 25 Creating the first Directive //JS Code angular.module(“myApp”,[]) .Controller(“myController”,[“$scope”,function($scope){ $scope.employee= {name:”Suresh”,dept:”Engineering”} }]) .directive(“myEmployee”,function(){ return { template:”<p>Name:{{employee.name}}</p><p>Department: {{employee.dept}}</p>” } }); <!-- HTML Code --> <div ng-controller=“myController”> <my-employee></my-employee> </div>
  • 26. 26 Directive in detail myApp.directive(“myDirective”,function(){ return { restrict:’E’ , //E- Element, A- Attribute, C- Class Name; Can have combination like ‘AC’ or ‘AEC’ template:”<div>any html </div>”, templateUrl:”templatesmytemplate.html”, //Can also be a function(elm,attr) which returns a url scope: {employeeInfo: ‘=info’}, //Other possible options are &attr (Callback) and @attr (One Way) link:function(scope, element, attrs, controller, transcludeFuction){ }, transclude:true, //Allow you to access scope outside the directive require:”^parentCtrl”, //Can be an array if multiple controllers to be passed controller:[‘$scope’,function($scope){ }], } });
  • 27. 27 Filters Filters allows us to manipulate and filter the presentation of our view. • Basic Filter {{totalCost | currency}} • Chaining filters {{totalCost | currency | filter1 | filter2}} • Extending filters with arguments {{totalCost | currency:”USD$”}} • Filtering from Controller/JS files $filter(number)(15,5) //Equivalent to {{15|number:5}}
  • 28. 28 AngularJS built-in filters • currency {{totalCost | currency:”$”:4}} • uppercase {{name| uppercase}} • lowercase {{name| lowercase}} • number {{totalCost|number:5}} • date {{createdOn | date:’fullDate’}} //Other format “yyyy”, “’Year:’yyyy,’Month:’MMM,’Day:’ EEEE” etc
  • 29. 29 AngularJS built-in filters • json {{employeeInfo | json}} • limitTo {{userFeedback | limitTo:50}} • filter {{ filter_expression | filter : expression : comparator}} <tr ng-repeat=“employee in employees| filter:searchText:strict"> <td> employee.name</td> </tr> • orderBy {{ orderby_expression | orderBy : expression : reverse}} <div ng-repeat=“emp in employees| orderBy:”-age”> emp.name</div>
  • 30. 30 Custom filters Writing your own filter is very easy. Just register a new filter factory function with your module. Internally, this uses the filterProvider. This factory function should return a new filter function which takes the input value as the first argument. Any filter arguments are passed in as additional arguments to the filter function. The filter function should be a pure function, which means that it should be stateless and idempotent
  • 31. 31 Custom filters Var myApp = angular.module(‘myApp’, []) myApp.filter('reverse', function() { return function(input, uppercase) { input = input || ''; var out = ""; for (var i = 0; i < input.length; i++) { out = input.charAt(i) + out; } // conditional based on optional argument if (uppercase) { out = out.toUpperCase(); } return out; }; }) myApp.controller(‘myController', ['$scope', function($scope) { $scope.employee = {name:‘Suresh‘, dept:’Engg’}; } ]); <div ng-controller=“myController"> <input ng-model=“employee.name" type="text"><br> No filter: {{name}}<br> Reverse: {{name |reverse}}<br> Reverse + uppercase: {{name |reverse:true}} <br> </div>
  • 32. 32 Internationalization & Localization (i18n & l10n) i18n is a process of developing products in such a way that can be localized for languages and cultures easily. l10n is the process of adapting application and text to enable their usability in a particular culture or linguistic market. AngularJS provides some functionality for i18n by allowing different pluralization rules through filters and by allowing users to quickly build custom solutions for string replacement. For this training we use a popular 3rd party library angular-translate. This library has a great organization mechanism and easily integrates into an existing AngularJS application. It too has the ability to interpolate values in strings. It has locale switching, asynchronous loading for string files, and allows you to translate through directives, filters, and their $translate service. It also currently has a larger user base and therefore has more guides and questions answered.
  • 33. 33 Internationalization & Localization (i18n & l10n) • Add reference to file <script src="path/to/angular-translate.js"></script> <script src="path/to/angular-translate-loader-static-files.min.js"></script> • Inject angular-translate module to app as dependency var app = angular.module('myApp', ['pascalprecht.translate']); • Configure the Module app.config(['$translateProvider', function ($translateProvider) { $translateProvider.useStaticFilesLoader({prefix: 'language/', suffix: '.json'}); $translateProvider.preferredLanguage('en'); $translateProvider.fallbackLanguage('en'); } ]) • Create appropriate resource bundle: “language/en.json”, “language/hi.json” • Use in HTML : <h1 translate="GREETING_MSG"></h1>
  • 34. Day 3
  • 35. 35 Services Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app. Angular services are: • Lazily instantiated – Angular only instantiates a service when an application component depends on it. • Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
  • 36. 36 Recipe to create services There are five recipe types that define how to create a Service object. • Value Recipe Value service can be used to make some data available across the application without polluting the global (window) namespace. var app = angular.module(“myapp”,[]); app.value(“user”,{name:admin,locale:en,roles:[]}); • Constant Recipe Constant service can be used to define application level constants. The main difference between value and constant is that value service can only be injected into other service or controller while constant can also be injected in module configuration function. var app = angular.module(“myapp”,[]); app.constant(“user”,{SERVER_PREFIX:”api/v2”});
  • 37. 37 Recipe to create services • Factory Recipe It allows use other services. When declaring factory name as an injectable argument we will be provided with the value that is returned by invoking the function reference passed in module.factory var app = angular.module(“myapp”,[]); app.factory(“factoryName”,function(){ return { sayHello:function(){ return “Hello!”; } } });
  • 38. 38 Recipe to create services • Service Recipe When declaring a service name as an injectable argument we will be provided with an instance of the function reference passed in module.service var app = angular.module(“myapp”,[]); app.service(“serviceName”,function(){ this.sayHello = function(){ return “Hello!”; } });
  • 39. 39 Recipe to create services • Provider Recipe When declaring a provider name as an injectable argument we will be provided with an object returned by $get call on new instance of the function reference passed in module.provider. Provider has advantage that they can be configured during module configuration phase. var app = angular.module(“myapp”,[]); app.provider(“providerName”,function(){ this.name = “Guest”; this.$get = function(){ var name = this.name; return { sayHello:function(){return “Hello “ + name}; } }; this.setName = function(name){this.name = name}; });
  • 40. 40 Let’s use all of them var app = angular.module(“myapp”,[]); //User provider type service in config app.config([“providerName”,function(providerName){ providerName.setName(“Suresh”); }]); //Use all types in controller app.controller([“$scope”,”providerName”,”factoryName”,”serviceName”, function($scope, providerName, factoryName, serviceName){ $scope.helloList = [ providerName.sayHello(), factoryName.sayHello(), serviceName.sayHello() ]; }]);
  • 41. 41 Routing and multiple views Routing is the most important feature of AngularJS framework which helps us developing Rich Interactive Applications (RIA). It enables partial page update by just changing a section of page. AngularJS provides a different module (Not part of core framework) which take case of routing. Steps for working with Routing: • Add reference to angular-route in your html file. <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script> • Inject ngRoute in your application module. var myApp = angular.module('myApp', ['ngRoute']);
  • 42. 42 Routing and multiple views • Configure your application for different routes myApp.config(['$routeProvider', function($routeProvider) { $routeProvider // route for the about page .when('/', { templateUrl : 'templates/home.html', controller : 'mainController' }) // Add other routes as required //Add default route .otherwise({ redirectTo: '/' }); }]);
  • 43. 43 Scopes Scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events. Scope is the glue between application controller and the view. During the template linking phase the directives set up $watch expressions on the scope. The $watch allows the directives to be notified of property changes, which allows the directive to render the updated value to the DOM. Each Angular application has exactly one root scope, but may have several child scopes. Scopes can propagate events in similar fashion to DOM events. The event can be broadcasted to the scope children or emitted to scope parents.
  • 44. 44 Scope lifecycle • Creation The root scope is created during the application bootstrap by the $injector. During template linking, some directives create new child scopes • Watcher registration During template linking directives register watches on the scope. These watches will be used to propagate model values to the DOM. • Model Mutation For mutations to be properly observed, you should make them only within the scope.$apply(). • Mutation observation At the end of $apply, Angular performs a $digest cycle on the root scope, which then propagates throughout all child scopes. • Scope destruction When child scopes are no longer needed, it is the responsibility of the child scope creator to destroy them via scope.$destroy() API
  • 45. Day 4
  • 46. 46 Event and Watchers Events and watchers are the great way to implement loose coupling in your application architecture. AngularJS has good support for publish/subscribe design pattern, in fact the whole AngularJS framework is based on this design pattern only. Fire Events: • $emit(name, args) Dispatches an event name upwards through the scope hierarchy notifying the registered listeners. The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, 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.
  • 47. 47 Event and Watchers • $broadcast(name, args) Dispatches an event name downwards to all child scopes (and their children) notifying the registered listeners. The event life cycle starts at the scope on which $broadcast was called. All listeners listening for name event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled. Listen on Events: • $on(name, listener) Listens on events of a given type. The event listener function format is: function(event, args...) The event object passed into the listener has multiple attribute like targetScope, currentScope, name, stopPropogation etc.
  • 48. 48 Event and Watchers Watch for changes: • $watch(watchExpression, listener, [objectEquality]) Watch Expression should be idempotent i.e. It should not change its value when called multiple times. The listener is called only when the value from the current watchExpression and the previous call to watchExpression are not equal. Inequality is determined according to reference inequality, strict comparison via the !== Javascript operator, unless objectEquality == true • $watchGroup(watchExpressions, listener) A variant of $watch() where it watches an array of watchExpressions. If any one expression in the collection changes the listener is executed. • $watchCollection(obj, listener); Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties)
  • 50. 50 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. AngularJS provides a supreme Dependency Injection mechanism. It provides its core components (services created using different recipes) which can be injected into each other as dependencies. Let’s have a look at some examples of DI: someModule.controller('MyController', ['$scope', 'greeter', function($scope, greeter) { // ... }]); var MyController = function($scope, greeter) { // ... } MyController.$inject = ['$scope', 'greeter'];
  • 51. 51 Promises A promise represents the eventual result of an operation. You can use a promise to specify what to do when an operation eventually succeeds or fails. Promises in AngularJS are provided by the built-in $q service. They provide a way to execute asynchronous functions in series by registering them with a promise object. • Deferred Object • A deferred object is simply an object that exposes a promise as well as the associated methods for resolving that promise. • It is constructed using the $q.defer () function and exposes three main methods: resolve(), reject(), and notify(). • The associated promise object can be accessed via the promise property.
  • 52. 52 Promises • Promise Object • We can obtain a Promise object by accessing promise property of deferred object (defer.promise). • We can register a callback function on the promise object that'll be executed after the async function completes. • Fulfill the Promise • We can call reslolve() method of deferred object (defer.reslve())to fulfill the promise. • Rejecting a Promise • We can call reject() method of deferred object [defer.reject(data)] to reject the promise in case of something goes wrong. • Resolving multiple promises • $q.all(promiseArray) returns a promise that is resolved when all of the promises in the specified array are resolved or any of them is rejected
  • 53. 53 Promises • Finally method • One of the guarantees promises make is that either the success or the error callback will be invoked, but never both. What happens if you need to ensure a specific function executes regardless of the result of the promise? You can do this by registering that function on the promise using the finally() method. • Promise chaining • One of the most powerful features of promises is the ability to chain them together. This allows the data to flow through the chain and be manipulated and mutated at each step. $http.get(‘someUrl’) .then(function(resp){ return $http.get(‘otherUrl’); }) .then(function(resp){ }) .catch(function(error){ });
  • 54. 54 Advanced Promises - Routing var getName = function(NameService) { return NameService.getName(); }; $routeProvider .when('/home', { templateUrl: 'home.html', controller: 'MainController' }) .when('/profile', { templateUrl: 'profile.html', controller: 'ProfileController‘, /* only navigate when we've resolved these promises */ resolve: { name: getName} })
  • 55. 55 Backend Communication Angular provides a rich built in support for communication with the server, it not only provides the low level mechanism which acts as building block to communicate with the servers, but it also provides built-in wrappers for communication with RESTful services • Communicating with $http The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP This service provides basic functionalities like: • GET • POST HEAD • DELETE • PUT • JSONP
  • 56. 56 Backend Communication • $http supported options $http({ method: string, // GET, POST, PUT, HEAD etc url: string, // URL of resource being requested params: object, // Query parameters, if not string goes as JSON string data: string or object, // Data to be sent as request message data headers: object, // Map representing the HTTP header transformRequest: function transform(data, headersGetter) or an array of functions, // Transforms request transformResponse: function transform(data, headersGetter) or an array of functions, // Transforms response cache: boolean or Cache object, // Boolean to turn cache on or off timeout: number, // Timeout to wait for response from server withCredentials: boolean });
  • 57. 57 Backend Communication • Communicating with RESTful Services using $resource Angular provides built in support to create a service using $resource object. This object provides common functionalities out of the box, without even writing a single line like Get, Save, Query, Remove, Delete $resource is an optional module in Angular defined in a separate file, so we have to include its JS file in our HTML file. <script src=” angular-resource.js”></script> The $resource service accepts 1 required parameter and 2 optional parameters: • URL required: The URL where the resource is available • Query params: Parameters to be passed with URL • Additional functions: Additional methods we want to add to the service.
  • 58. Day 5
  • 59. 59 AngularUI Angular UI is project that includes UI modules developed to used in AngularJS Applications. It includes UI-bootstrap that is Bootstrap UI elements for AngularJS. It also includes many other Angular variants of famous JQuery UI modules. AngularUI is an organization that originally started off as one project to consolidate efforts people were making early on across the entire community to create defacto widgets and directives for AngularJS (like jQueryUI is to jQuery). Although it started off as one project with multiple widget wrappers, it's evolved into an organization with multiple teams and projects with different focuses.
  • 60. 60 AngularUI – UI Bootstrap • It is a set of native AngularJS directives based on Bootstrap’s markup and CSS. • The only dependency for this is AngularJS lib file and Bootstrap CSS file. • Installation • Download the library file from github repo (https://github.com/angular- ui/bootstrap/tree/gh-pages) and include in index.html file. • Download the bootstrap css lib file and include in head section of your index.html • Define the dependency in your module • angular.module('myModule', ['ui.bootstrap']); • Find a detailed list of features with demo refer to below link • http://angular-ui.github.io/bootstrap/
  • 61. 61 AngularJS module pattern • In AngularJS world EVERYTHING is a module. • AngularJS modules can be defined in any order, including dependency modules that haven’t been defined yet. Module Pattern in JavaScript (self executing functions): • Variable scope encapsulation. • Imports any dependency through functions parameters. • Exports its own functionality as a return statement. var MyModule = ( function( dependency ) { var _otherModuleVar = dependency || {}; var _privateMethod = function(){/* Function logic goes here */ }; return { publicMethod:function(){ _privateMethod() } }; })(otherModule);
  • 64. 64 AngularJS application organization A Better Structure for large application
  • 65. 65 Reorganize our Sample Application Create a directory structure and move the files at their proper place
  • 66. 66 Reorganize our Sample Application home.js
  • 67. 67 Reorganize our Sample Application about.js
  • 68. 68 Reorganize our Sample Application app.js
  • 69. 69 Reorganize our Sample Application index.html
  • 70. 70 Testing AngularJS has very good support of testing as it is written with testability in mind. • Environment Setup • Karma (Test Runner) • Jasmine • Protractor (End to End test Runner)
  • 73. 73 Writing Unit Test:- Check if controller injected
  • 74. 74 Writing Unit Test:- Testing Directive
  • 75. 75 Run Unit Test • Execute command “npm test”
  • 76. 76 End to End Testing- Protractor config
  • 77. 77 End to End Testing- Write Scenarios
  • 78. 78 Run End to End • Execute command “npm run protractor”
  • 79. Day 6
  • 80. 80 Common Use Cases Sharing Models Between Nested Controllers Use JavaScript objects instead of primitives or direct $parent scope references.
  • 81. 81 Common Use Cases Sharing Code Between Controllers using Services Utilize a Service to implement your business logic and use dependency injection to use this service in your controllers.
  • 82. 82 Common Use Cases Changing the DOM in Response to User Actions Implement a directive my-widget that contains an example paragraph of text we want to style.
  • 83. 83 Common Use Cases Passing Configuration Parameters Using HTML Attributes Use the attribute-based directive and pass an attribute value for the configuration. The attribute is passed as a parameter to the link function.
  • 84. 84 Common Use Cases Directive-to-Directive Communication We implement a directive basket with a controller function and two other directive orange and apple which “require” this controller
  • 85. 85 Common Use Cases Using Route Location to Implement a Navigation Menu Use the $location service in a controller to compare the address bar URL to the navigation menu item the user selected.
  • 86. 86 Common Use Cases Listening on Route Changes to Implement a Login Mechanism Implement a listener on the $routeChangeStart event to track the next route navigation. Redirect to a login page if the user is not yet logged in.
  • 87. 87 Common Use Cases Editing Text In-Place using HTML5 ContentEditable Implement a directive for the contenteditable attribute and use ng-model for data binding.
  • 88. 88 Common Use Cases Displaying a Modal Dialog Use the angular-ui module’s nice modal plugin, which directly supports Twitter Bootstrap.
  • 89. 89 Common Use Cases Displaying a Loading Spinner An Angular.js interceptor for all AJAX calls can be used, which allows you to execute code before the actual request is started and when it is finished.
  • 90. 90 Dependency Management • Dependency Management • Bower • Install bower by from command prompt “npm install bower -g” • Install dependency by command “bower install” bower.json .bowerrc
  • 91. 91 Building and Minification • Building and Minification • Grunt • npm install grunt-ts –save • npm install grunt-cli –g Define the required packages as devDependency in package.json and Run “npm install”
  • 95. 95 Making changes in Index.html
  • 96. 96 Building using Grunt • Building • Run “grunt” command • It will execute default task defined in gruntfile.js • We defined “grunt.registerTask('default', ['uglify','string-replace']);” so minification and string replace task will be executed.
  • 97. 97 What’s Next !!! The next version of AngularJS, “Angular” is already released which includes lot of improvement and learnings from AngularJS framework. Soon, we will have learning sessions on Angular as well.  HAPPY LEARNING 