SlideShare a Scribd company logo
1 of 146
ANGULAR JS
GET STARTED
By,
Santha Mani
INTRODUCTION
Angular JS is a JavaScript framework you can use to
build applications, but run in a web browser
using HTML.
The Angular JS framework started as a project
inside of Google, but it's now an open source
project so anyone can contribute to Angular or use
Angular in their own applications.
BENEFITS
Used for Single page and line of pages of application
Dependency Injection
Two-way binding
Testing
MVC
Controlling the DOM elements like Directives,
Filters, Services, Controllers,…
ANGULARJS.ORG – HOME FOR
ANGULAR
angularjs.org - this is where you can
find links to mailing lists,
find the documentation,
find a Download button if you want to bring all of
the Angular libraries down and use them locally,
and there's also a link to GitHub where the raw
source code lives.
A related website you might be interested in is,
builtwith.angularjs.org. This website includes
pictures and links to other public websites that have
been built with AngularJS.
AN ANGULAR APPLICATION
There are only two requirements for adding Angular JS
to a web page
<script> tag pointing to angular.js.
need to add an ng-app attribute somewhere in your
HTML
ng-app, in Angular terminology, is called a directive,
and it is just one of many directives that Angular
provides.
The ng prefix is short for Angular.
EXAMPLE
EXAMPLE
Angular found that particular binding expression,
that's what we call it, and an output into the web
page.
The double curly braces are what some people
would call mustaches or handlebars, they are
binding expressions in Angular.
 {{ expression }} – binding expression
ng-init – initializes the application in the current
scope.
<!DOCTYPE html>
<html>
<head>
<title>Angular JS - Arrays(StringS)</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></scri
pt>
</head>
<body>
<div ng-app="" ng-init="program=['HML','CSS','Jquery','AngularJs']">
<div ng-app="" ng-init="number=[5,25,50,75,100]">
<p>
This is fist program:<span ng-bind="program[3]"></span><br>
This is last program:<span ng-bind="program[1]"></span>
</p>
<p>Single quotes to be mentioned for sring values in the array declaration</p>
</div>
</body>
</html>
MODULE
Modules are the basic building block of Angular.
Everything exists inside of our module.
A module is a container for different parts of your
application i.e., controller, services, directives,
filters etc..
Specifies the bootstrapping
SYNTAX
var myApp = angular.module(“myModule”,[]);
myModule = name of our Module
Empty square braces [] = dependents of our
module
EXAMPLE
var myApp = angular.module('myModule', []);
<!DOCTYPE html>
<html ng-app = "myModule">
<head>
<script data-require="angularjs@1.5.8" data-semver="1.5.8"
src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js">
</script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body >
<h1>Hello Plunker!</h1>
{{ 8/4}}
</body>
</html>
CONTROLLER
The job of a controller is To build a model for View.
It does by attaching to the $scope object.
$scope is not a model it’s the data that we attach to
$scope is the model.
CREATING A CONTROLLER
ng-controller is an attribute that we place into our
HTML, we can specify the name of a controller that
we want to take control of some area of the HTML
Angular will invoke the controller function when it
needs to create a controller to manage an area of the
webpage.
$scope is a component provided by Angular. What we
can do with the scope argument is assign our model
to the object.
EXAMPLE
var myApp = angular.module('myModule', []);
myApp.controller('myController', function($scope)
{
$scope.message = "Hello Angular";
});
<!DOCTYPE html>
<html ng-app="myModule">
<head>
<script data-require="angularjs@1.5.8" data-semver="1.5.8"
src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js">
</script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
{{ 8/4}} <br>
<div ng-controller="myController">
{{message}}
</div>
</body>
</html>
EXAMPLE
Now we've seen a controller in action, and we see that
the primary responsibility of a controller is to set up
the model on our $scope object.
Angular passes $scope to our controller function, and
our controller manipulates that scope.
It only manipulates $scope by attaching a model.
And then we use binding expressions to move data
from the $scope into the view.
EXAMPLE
///<refereence path="angular.min.js"/>
var myApp=angular.module("myModule",[ ]);
myApp.controller("myController", function($scope)
{
var employee = { firstName: "Avinash Kumar",
lastName: "Gaddamanugu",
gender: "Male“
};
$scope.employee=employee;
});
<!DOCTYPE html>
<html ng-app="myModule">
<head> <title>Complex ng-model</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angula
r.min.js"></script>
<script src="angular.js"></script>
<script type="text/javascript" src="ComplexScripts.js"></script>
</head>
<body>
<div ng-controller="myController">
<div> First Name: {{ employee.firstName }} </div>
<div> Last Name: {{ employee.lastName }} </div>
<div> Gender: {{ employee.gender }} </div>
</div>
</body>
</html>
CAPABILITIES
Multiple Controller
Complex Controller
Nested Controller
DIRECTIVES
Controls the DOM elements (behavior)
It is prefixed by ng.
Eg: ng-init, ng-app, ng-model, ng-repeat
The ng-app directive initializes an AngularJS
application.
The ng-init directive initializes application data.
The ng-model directive binds the value of HTML
controls (input, select, textarea) to application data.
NG-SRC
The purpose of the ng-source directive is that once
Angular is up and running, once it has evaluated this
expression, then it will come in and set the actual
source attribute for that image and the image should
be successfully downloaded and you'll avoid these
404 errors.
So ng-source is just a directive to set the source of an
image when there's a data binding expression
involved.
TWO-WAY BINDING
Keeps the model and the view sync all the time.
Change in model updates the view and change in view
updates the model.
Model
View
Change in
View updates
View
Change in
View updates
Model
NG-MODEL
Bind the value of an input field to a variable created in
Angular JS
Ng-model - always keep your data in sync
It can be apply to inputs, select and textarea
Example
Ng-model.html, ng-model.js
Also can specify in complex way
Complex Module & Controller.html & Complex ng-
model.js
NG-MODEL CAN PROVIDE TYPE VALIDATION FOR
APPLICATION DATA (NUMBER, E-MAIL, REQUIRED).
<!DOCTYPE html >
<html ng-app="" >
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js
"></script>
<body>
<form name="myForm">
Email:
<input type="email" name="myAddress" ng-model="text">
<span ng-show="myForm.myAddress.$error.email">Not a valid e-
mail address</span>
</form>
<p>Enter your e-mail address in the input field. AngularJS will display
an errormessage if the address is not an e-mail.</p>
</body>
</html>
NG-MODEL DIRECTIVE CAN PROVIDE STATUS FOR APPLICATION
DATA (INVALID, DIRTY, TOUCHED, ERROR)
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<form ng-app="" name="myForm" ng-init="myText = 'post@myweb.com'">
Email:
<input type="email" name="myAddress" ng-model="myText" required>
<p>Edit the e-mail address, and try to change the status.</p>
<h1>Status</h1>
<p>Valid: {{myForm.myAddress.$valid}} (if true, the value meets all criteria).</p>
<p>Dirty: {{myForm.myAddress.$dirty}} (if true, the value has been changed).</p>
<p>Touched: {{myForm.myAddress.$touched}} (if true, the field has been in focus).</p>
</form>
</body></html>
NG-MODEL DIRECTIVE PROVIDES CSS CLASSES
FOR HTML ELEMENTS, DEPENDING ON THEIR
STATUS
ng-model directive adds/removes the following
classes, according to the status of the form field
ng-empty
ng-not-empty
ng-touched
ng-untouched
ng-valid
ng-invalid
ng-dirty
ng-pending
ng-pristine
NG-REPEAT
Similar to foreach() loop in C#.
Table format
Ng-repeat.html & ng-repeat.js
List Format
Ul-ng-repeat.html & ul-ng-repeat.js
NG-OPTIONS
Used for filling a dropdown list with options.
Selected value to be an object
For key-value pair
Using an object as the data source, x represents the key, and y
represents the value:
<select ng-model="selectedCar" ng-options="x for (x, y) in cars">
</select>
The selected value will always be the value in a key-value pair.
The options in the dropdown list does not have to be the key in a
key-value pair, it can also be the value, or a property of the
value object
<select ng-model="selectedCar" ng-options="y.brand for (x, y) in
cars">
</select>
NG-OPTIONS VS NG-REPEAT
The ng-options directive was made especially for
filling a dropdown list with options.
The ng-repeat directive repeats a block of HTML code
for each item in an array, it can be used to create
options in a dropdown list.
Dropdowns made with ng-options allows the selected
value to be an object, while dropdowns made from
ng-repeat has to be a string.
NG-OPTIONS VS NG-REPEAT
<select ng-model="selectedCar">
<option ng-repeat="x in cars"
value="{{x.model}}">{{x.model}}</option>
</select>
<select ng-model="selectedCar" ng-options="x.model for
x in cars"></select>
CUSTOM DIRECTIVES
Create New Directives
In addition to all the built-in AngularJS directives, you
can create your own directives.
New directives are created by using
the .directive function.
To invoke the new directive, make an HTML element
with the same tag name as the new directive.
When naming a directive, you must use a camel case
name, w3TestDirective, but when invoking it, you must
use -separated name, w3-test-directive
EXAMPLE<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<body ng-app="myApp">
<w3-test-directive></w3-test-directive>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "<h1>Made by a directive!</h1>"
};
});
</script>
</body>
</html>
CUSTOM DIRECTIVE
You can invoke a directive by using:
Element name
<w3-test-directive></w3-test-directive>
Attribute
<div w3-test-directive></div>
Class
<div class="w3-test-directive"></div>
Comment
<!-- directive: w3-test-directive -->
You must add the value "C" to the restrict property
to be able to invoke the directive from a class
name.
RESTRICTIONS
Restrict your directives to only be invoked by some
of the methods
The legal restrict values are:
E for Element name
A for Attribute
C for Class
M for Comment
By default the value is EA, meaning that both
Element names and attribute names can invoke
the directive.
EVENT HANDLING – NG-CLICK
An expression that’s going to be a function call
Example
Events.html & events.js
In addition to these built-in directives, angular allows you to write
custom directives.
Custom directives to perform activities like drag-and-drop, or custom
directives that can wrap bootstrap widgets, or media players, or
wrappers for google maps.
FILTERS
Used to transform data
Can do 3 different things
Format data
Sort data
Filter data
Can be used with a binding expression or a
directive.
To apply a filter use pipe (|) character
{{ expression | filter : parameter }}
DATE
YYYY - 4 digit year – Ex: 1992
YY - 2 digit year –Ex: 1992:-92
MMMM – Full name (January – December)
MMM – Jan – Dec
MM – 01-12
M – Numerical Formats (1-12 ) (No leading zeros)
dd – 01 -31
d – 1 – 31 (No leading zeros)
THE FILTER FILTER
The Filter filter selects a subset of an array.
The Filter filter can only be used on arrays, and it
returns an array containing only the matching
item.
LimitTo Filter
limitTo filter: Can be used to limit the
number of rows or characters in a string.
{{ expression | limitTo : limit : begin }}
ADDING FILTERS TO
DIRECTIVES
Filters are added to directives, like ng-repeat, by using
the pipe character |, followed by a filter.
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
SORTING ROWS IN A TABLE
tablesorting.html
tablesorting.js
SORTING BY MULTIPLE PROPERTIES
Sortingdata.html
Sortingdata.js
Multiplesort.html
Multiplesort.js
SEARCH MULTIPLE PROPERTIES
Searchfilter.html
Searchfilter.js
CUSTOM FILTERS
Customfilter.html
Customefilter.js
ng-hide & ng-show
Used to control the visibility of the HTML element.
Hide Salary: <input type="checkbox" name="checkbox" ng-model="hideSalary" />
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
<th>City</th>
<th ng-hide="hideSalary">Salary</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="emp in employees">
<td> {{ emp.name }} </td>
<td> {{ emp.gender }} </td>
<td> {{ emp.city }} </td>
<td ng-hide="hideSalary"> {{ emp.salary }} </td>
</tr>
</tbody>
ng-hide & ng-show
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
<th>City</th>
<th ng-hide="hideSalary">Salary</th>
<th ng-show="hideSalary">Salary</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="emp in employees">
<td> {{ emp.name }} </td>
<td> {{ emp.gender }} </td>
<td> {{ emp.city }} </td>
<td ng-hide="hideSalary"> {{ emp.salary }} </td>
<th ng-show="hideSalary">####</th>
</tr>
</tbody>
ng-include
Used to embed an HTML page into another HTML
page.
Used when we want specific view in multiple pages
of our application
The value of the ng-include can be
The name of HTML page that to be reusable
A property on the $scope object that points to the
reusable HTML page.
SERVICE
Is a an object that can be reused within an
application.
Eg: Math()- provides services to add number
A service in angular is an object that provides some
sort service that can be reused in a angular
application.
Angular JS has about 30 built-in services.
NEED OF SERVICE
Single Responsibility Condition: States that an object
should have a single responsibility.
Services encapsulate reusable logic that doesn’t
belong anywhere else (i.e., directives, filters, views,
model & controller)
Benefits
Reusability Eg: $http
Dependency Injection
Testability
$location Service
return information about the location of the current web page
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>The url of this page is:</p>
<h3>{{myUrl}}</h3>
</div>
<p>This example uses the built-in $location service to get the absolute url of the page.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $location) {
$scope.myUrl = $location.absUrl();
});
</script>
$interval Service
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>The time is:</p>
<h1>{{theTime}}</h1>
</div>
<p>The $interval service runs a function every specified
millisecond.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});
</script>
</body>
$timeout Service
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>This header will change after two seconds:</p>
<h1>{{myHeader}}</h1>
</div>
<p>The $timeout service runs a function after a sepecified number of
milliseconds.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "Hello World!";
$timeout(function ()
{
$scope.myHeader = "How are you today?";}, 2000);
});
</script>
$http Service
<div ng-app="myApp" ng-controller="empController">
<table>
<tr><th>Name</th></tr>
<tr ng-repeat=“emp in empployees”>
<td>{{emp.name}}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http ,$log) {
$http.get(“data.json)then(function (response) {
$scope.employees = response.data;
});
});
</script>
PROMISE OBJECT
$http service returns a promise object as the
functions are executed asynchronously.
A promise object is an object that promises to give
you some result in the future, and that result
might be the data that you need, or the result
might be an error if the server was unavailable.
The way I find out is to call a then() method on my
promise and pass the then() method a function
that will be called in the future.
EG: PROMISE OBJECT
var myApp=angular.module(“serviceApp”,[])
.controller(“serviceCtrl”,function($scope, $http){
$http.get(‘sample.html’)
.then(function(scope)
{
$scope.myWelcome = response.data;
});
});
Function is called when the request completed
successfully, we get response from the server
Ex: http://andyshora.com/promises-angularjs-explained-as-cartoon.html
CUSTOM SERVICES
An AngularJS service can be created or registered or
created in four different ways,
Using the service() method
Using the factory() method
Using the provider() method
Using the value() method
Using the constant() method
service() vs factory()
Using the service() method uses the function
constructor and it returns the object or instance of
the function to work with.
Using the factory() method uses the returned value
of the function. It returns the value of the
function returned after the execution
NORMAL SERVICE
var myApp = angular.module("myModule", [])
.controller("myController", function($scope){
$scope.transformString = function(input){
if(!input)
{
return input;
}
var output = "";
for (var i = 0; i < input.length; i++)
{
if(i>0 && input[i] == input[i].toUpperCase()) {
output = output + " ";
}
output = output + input[i];
}
$scope.output = output;
}
});
NORMAL SERVICE CALL
In this we have two problems
The controller code become complex and large
If we want to reuse this code in any controller we
have to duplicate that code within that controller. At
the moment we start duplicating the maintainability
of the application will be loss.
To overcome this we encapsulate the service and
inject that service into any controller where we
want to use.
SERVICE/FACTORY METHOD
It is used for creating the custom service and register
this with angular.
myApp.factory(‘stringService’, function(){
return
{
processingString: function(input){
------
----
}
};
)}
SYNTAX
var myApp = angular.module(“myModule”,[])
.controller(“myCtrl”,function($scope, stringService)
{
$scope.transformString = function(input)
{
$scope.out = stringService.processingString(input);
}
});
$http get()
In Angularjs get ($http.get()) service or method is used to get data from
remote HTTP servers.
var app = angular.module('getserviceApp', []);
app.controller('getserviceCtrl', function ($scope, $http) {
// Simple GET request example:
$http({
method: 'GET',
url: '/sampleUrl',
data: 'parameters'
})
.then(function success(response) {
// this function will be called when the request is success
},
function error(response) {
// this function will be called when the request returned error status
});
});
SYNTAX
method - This property is used to define required operator like
get or send data. In angularjs we have different methods
available.
url - We need to send url of http server to perform required
operations.
data - If we have any parameters to send and get data from
request url we will pass it using this parameter.
then - In then property we will do our coding based on
response status either success or failure. If it is success it
will execute first method or in case if we get error second
method will execute.
$http.get Properties
config - The configuration object is used to generate the
request.
data - It’s string or an object which is used to carry
response from the server.
headers - This function is used to get header information.
status - This property is used to get HTTP status code of the
response.
statusText - This property is used to get HTTP status text of
the response.
$http post() method
The $http.POST() services are used to send the data
to a specific URL and expects the resource at that
URL to handle the request that means we can say
that POST method is used to Insert new data
based on given URL
SYNTAX
var app = angular.module('putserviceApp', []);
app.controller('putserviceCtrl', function ($scope, $http)
{
// Simple Post request example:
var url = 'posturl', data = 'parameters',config='contenttype';
$http.post(url, data, config)
.then(function (response)
{
// This function handles success
},
function (response) {
// this function handles error
});
});
$http.post() Properties
config - The configuration object is used to
generate the request.
data - It’s either string or an object.
headers - We can get header information.
status - We can get HTTP status code of the
response.
statusText - Get HTTP status text of the response.
$http.put() method
The $http.put() service in angularjs is used to upload
a files to server and update existing data in server
based on given URL.
Generally $http.put method not allowed by many
servers due to security reasons.
SYNTAX
var app = angular.module('putserviceApp', []);
app.controller('putserviceCtrl', function ($scope, $http) {
// Simple Put request example:
var url = 'puturl', data = 'parameters',config='contenttype';
$http.put(url, data, config).then(function (response)
{
// This function handles success
},
function (response) {
// this function handles error
});
});
SYNTAX
url - Used to send url of http server to perform
required operations.
data - This property to send required parameters to
requested url.
config - By using this property we can change
content-type.
After execution of our $http.put request we will get
response based on that response status our
success and failure methods will execut
$http put() Properties
config - The configuration object is used to generate
the request.
data - It’s either string or an object.
headers - We can get header information.
status - We can get HTTP status code of the
response.
statusText - Get HTTP status text of the response.
$http.jsonp() Service
In angularjs jsonp or json with padding service is
used to make cross domain requests from client
browser.
By using $http.jsonp service in angularjs we can get
data in json format and the server whatever we are
requesting should support jsonp requests
otherwise it’s worthless
BENEFIT
Generally now a days browsers are blocking access
data from a server which is in different domain
due to same origin policy.
By using angularjs $http.jsonp method we can
access data from different domain without having
any access problems.
SYNTAX
var app = angular.module('jsonserviceApp', []);
app.controller('jsonCtrl', function ($scope, $http) {
//Call the service to get data in json
var url = "Some API Url" + "?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function (data, status, headers, config) {
$scope.details = data;
})
.error(function (data, status, headers, config) {
$scope.statusval = status;
});
});
JSON_CALLBACK
“callback=JSON_CALLBACK” to url to make a service
request.
AngularJs is having its own callback pattern, so it will
follow that pattern to handle jsonp callbacks.
In angularjs always we need to
send callback=JSON_CALLBACK with url while
requesting jsonp service.
Using this pattern we handle the JSONP call-back and
its call-back is called JSON_CALLBACK.
Angularjs Success / Error Functions
In angularjs while using $http services we have
success() and error() functions with then property
to display the success and failed response of
request information.
In angularjs we can use success and error methods
with http GET, POST, PUT, DELETE, JSONP and
PATCH services.
SYNTAX
var app = angular.module('getserviceApp', []);
app.controller('getserviceCtrl', function ($scope,
$http) {
// Simple GET request example:
$http.get("url").then(function success(response) {
// this function will be called when the request is
success
},
function error(response)
{
// this function will be called when the request returned
error status
});
});
anchorScroll
Used to jump to specified element on the page.
var myApp=angular.module("myModule",[ ]);
myApp.controller("myController", function($scope,
$location, $anchorScroll)
{
$scope.scrollTo = function(scrollLocation)
//mention the id of the element {
$location.hash(scrollLocation);
$anchorScroll();
}
});
CLIENT AND SERVER ROUTING
Server-Side routing:
A client would request a
webpage or other
resource from the server
using a URL and the
server retrieves the
resource and sends it
back to the client. Often
this meant that an entire
webpage would be sent
back to the browser after
each request to the server.
CLIENT – SIDE ROUTING
Client – Side Routing
However, when using a client-side framework like
Angular, the requests to the server are of often for
smaller bits of information rather than entire
webpages and all of their related resources.
Client-side routing doesn't replace server-side routing.
All web applications still interact heavily with servers
and those servers still need to accept a URL and use it to
locate and return the resource needed by the client.
SERVER-SIDE ROUTING WITH SPAS
AND CLIENT-SIDE ROUTING.
SPA stands for Single Page Application.
The idea behind a SPA is that it appears to the user
as if it's one page in the browser and you only
update portions of that page as the user interacts
with the application.
ngRoute
ngRoute is its own Angular module, and stored in
its own JavaScript file.
ngRoute module helps your application to become a
Single Page Application.
The ngRoute module routes your application to
different pages without reloading the entire
application.
WHAT DO I NEED
To make your applications ready for routing, you must
include the AngularJS Route module:
<script src="https://ajax.googleapis.com/ajax/libs/angul
arjs/1.4.8/angular-route.js"></script>
Then you must add the ngRoute as a dependency in the
application module::
var app = angular.module("myApp", ["ngRoute"]);
$routeProvider
Define the $routeProvider using the config method of
application. Work registered in the config method
will be performed when the application is loading.
ngRoute – provides the routing this our dependency
$ routeProvider – used to configure routes
$routeProvider to configure routes
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"
})
.when("/red", {
templateUrl : "red.htm"
})
.when("/green", {
templateUrl : "green.htm"
})
.when("/blue", {
templateUrl : "blue.htm"
});
});
EXAMPLE
var myApp=angular.module("myModule",["ngRoute"])
.config(function($routeProvider,$locationProvider)
{
$routeProvider
.when("/",{
templateURL : "Template/home.html",
controller : homeController;
}
});
WHERE DOES IT GO?
Application needs a container to put the content
provided by the routing.
This container is the ng-view directive.
There are three different ways to include the ng-
view directive in your application
<div ng-view></div> as attribute
<ng-view></ng-view> as tag
<div class="ng-view"></div> as class
USING CONTROLLERS
With the $routeProvider you can also define a controller for
each "view".
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"
})
.when("/london", {
templateUrl : "london.htm",
controller : "londonCtrl"
})
.when("/paris", {
templateUrl : "paris.htm",
controller : "parisCtrl"
});
});
app.controller("londonCtrl", function ($scope) {
$scope.msg = "I love London";
});
app.controller("parisCtrl", function ($scope) {
$scope.msg = "I love Paris";
});
otherwise()
otherwise method, is the default route when none of
the others get a match
If you try to navigate to route that is not configured,
any partial template will not be injected because
angular doesn’t know the route of template/site.
.otherwise({
redierctTo : “/main”;
})
INLINE TEMPLATE
The template property, allows you to write HTML directly
in the property value, and not refer to a page.
Eg:
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
template : "<h1>Main</h1><p>Click on the links to
change this content</p>"
});
})
$route Service
It has two methods, reload and updateParams
The updateParams method allows you to reload the
current URL with a new set of route parameters.
You pass the new parameters as properties on an object
to the updateParams method. The property names that
match parameter names you've configured on the route,
will then have the new values inserted into the URL.
The reload method will reload the current route.
This will simply reload the current route within your
Angular app, which mean it will make any necessary
network calls, process route parameters, and generally
treat the route as if you were visiting it for the first time.
$route Service - Parameters
The current property :
gives you a reference to the current route definition
and allows you to exam the controller for the route,
scope, and other variables used when creating the
route's controller.
The routes property :
is an object containing all of the route definitions for
your application. You can use it to see all of the routes
you've configured on the route provider.
reload()
By using the reload() function on the route service
give us the ability to refresh the data on the home
page of the app.
.controller(“homeController, function($http,$route)
var vm = this;
vm. reloadData = function()
{
route.reloadData();
}
Route change
This is used when we are filling long form
application.
This is created with a alert window asking for OK
and Cancel
OK: navigate to next partial template/page
Cancel: stays in current page
Route Change
When a route change occurs, then two events are
generated
$routeChangeStart
$locationChangeStart
The only difference between two events is the ‘next’
and ‘current’ parameters.
The $locationChangeStart event ‘next’ and ‘current’
parameters has got complete next and current
URL’s
$routechangestart()
.controller(“studentController”,
function($http,$scope,$route)
$route.$on(“$routeChangeStart”,
function(event,next,current)
{
if(!confirm(“Are you sure to navigate”))
{
event.preventDefault();
}
}
NAVIGATION PAGE
We can also specify to which page we are navigating.
.controller(“studentController”,
function($http,$scope,$route)
$route.$on(“$routeChangeStart”,
function(event,next,current)
{
if(!confirm(“Are you sure to
navigate” + next.$$route.orginalPath))
{
event.preventDefault();
}
}
$locationchangestart()
.controller(“studentController”,
function($http,$scope,$route)
$route.$on(“$locationChangeStart”,
function(event,next,current)
{
if(!confirm(“Are you sure to navigate”))
{
event.preventDefault();
}
}
NAVIGATION PAGE
We can also specify to which page we are navigating.
.controller(“studentController”,function($http,$scope,$route)
$route.$on(“$locationChangeStart”,
function(event,next,current)
{
if(!confirm(“Are you sure to
navigate” + next))
{
event.preventDefault();
}
}
ROUTE RESOLVE
If the components of the application i.e., database
server, application and the client present in
different machines and a network latency then
the data few seconds to load.
If the components of the application are in local
machine, then there will not be any network
latency.
REMOVE (#) SYMBOL
Enable html5mode
$locationProvider.html5mode(true);
Remove # in anchor tag
Include URL rewrite rule in web.config
Set base href element to the location of single page
application
<base href=“/” />
all the partial templates are present within the root
element
ANGULAR CASE-INSENSITIVE
By default Angular is case sensitive
To make a route to case insensitive make it true.
$routeProvider.caseInsensitiveMatch = true;
CONTROLLER AS SYNTAX
There is another mechanism to make the members
of the controller available in the view i.e.,
Controller As Syntax
With this there is no need for injecting the $scope
object.
Instead we use ‘this’ keyword.
<!DOCTYPE html>
<html ng-app = “myModule”>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.m
in.js">
</script>
<script>
var app = angular
.module (“myModule”,[])
.controller (“myController”, function(){
this.message = “Angular JS Tutorial”;
});
</script>
<body ng-controller = “myController as myCtrl”>
<h2> {{ myCtrl.message }} </h2>
</body>
</html>
NESTED CONTROLLER
<div ng-controller="countryController">
{{name}}
<div ng-controller="stateController">
{{name}}
<div ng-controller="cityController">
{name}}
</div
</div>
</div>
CONTROLLER vs SCOPE
Controller as syntax is new & released 1.2.0 officially.
$scope is the old technique & is available since the
initial version of angular is released.
Controller as syntax makes code more readable.
If you want to use $scope object it is to be injected
into the controller function, where as with
controller as syntax there is no need for such
injection, unless it is for some thing else.
$scope
var myApp=angular.module("myModule",[])
.controller("countryController", function($scope){
$scope.name = "India";
});
Controller as syntax
var myApp=angular.module("myModule",[])
.controller("countryController", function(){
this.name = "India";
});
CONTROLLER vs SCOPE
Though we are using controller as syntax; don’t
think that angular won’t use $scope. It is using
but it is hiding.
That is in controller as syntax we aliasing the
controller: myController as myCtrl
This cityCtrl is reference variable pointing to the
myController. Angular will take this reference
and attach to the $scope object.
$scope vs $rootscope
$rootScope: Is available globally (for all controllers)
$scope: Is available only to the controller that is
created.
var myApp = angular.module("myModule", [])
.controller("redController", function($scope, $rootScope)
{
$scope.redColor = "I am Red";
$rootScope.rootScopeColor = "I am Root Scope Color";
})
.controller("greenController", function($scope)
{
$scope.greenColor ="I am Green";
})
<body>
<div ng-controller="redController">
Root Scope : {{ rootScopeColor }}<br>
Red Color Controller : {{ redColor }}<br>
Green Color Controller :{{ greenColor }}
</div>
<br>
<div ng-controller="greenController">
Root Scope : {{rootScopeColor}}<br>
Green Color Controller : {{greenColor}}<br>
Red Color Controller :{{redColor}}
</div>
</body>
Angular $ui-router
The ui-router is a 3rd party routing framework for
Angular JS
ui-router implements routing based on the state of
the application where as ngRoute implements
routing based on the route URL.
$ui-router vs ngroute
ngRoute implements routing based on the route
URL that means we use view & routes that are
tied to the application URL.
ui-router use the routes that are not tied to the
application URL that means parts of the sites can
be changed even if the URL doesn’t change.
How to get $ui-router
WHAT DO I NEED
The first thing you need to do is reference the UI-Router
JavaScript file.
Get the CDN link from:
https://cdnjs.com/libraries/angular-ui-router
<script
src=“https://cdnjs.cloudflare.com/ajax/libs/angular-ui-
router/0.3.2/angular-ui-router.js”></script>
(OR)
<script
src=“https://cdnjs.cloudflare.com/ajax/libs/angular-ui-
router/0.3.2/angular-ui-router.min.js”></script>
ADD A MODULE DEPENDENCY ON UI-
ROUTER.
$ui-view Directive
Finally, you'll need to add a ui-view directive to
your page. This is the rough equivalent of using
the ngView directive when working with
ngRoute.
It gives the router a place to insert views into your
page.
“ https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.min.js “ >
CONFIGURING STATES
Call the config function module, and inject into it the
state $stateProvider service that comes with UI-
Router.
It has two parameters
The first parameter to the function is the name you
want to give the state.
The second parameter to the state function is a
configuration object.
CONFIGURING STATES
var myApp = angular.module(“myModule”,[‘ui-roter’])
.config(function($stateProvider){
$stateProvider
.state(“home” {
url: “/home”,
templateUrl: “Templates/home.html”,
controller: “homeController”,
controllerAs: “homeCtrl”
})
});
Inline $ui-router
var myApp = angular.module(“myModule”,[‘ui-roter’])
.config(function($stateProvider){
$stateProvider
.state(“home” {
url: “/home”,
template: “Hello Angular”,
controller: “homeController”,
controllerAs: “homeCtrl”
})
});
$ui-router Parameters
Define the sate with URL parameter
.state(“studentDetails”,{
url:”/studentdetail/:id”,
templateUrl:”Templates/studentDetails.html”,
controller: “studentDetailsController”,
controllerAs:”studentDetailsCtrl”
})
Link to the state with URL parameter
<ul>
<li ng-repeat=“studentDetailsCtrl.students”>
<a ui-sref=“studentDetails({id:student,id})”></a>
</li>
</ul>
$ui-router Parameters
Read the specific parameter value from controller function, call the
web-service method(if any) & id value & then retrieve that specific
parameter.( Eg :student details)
controller(“studentDetailsController”,function($scope,$stateProvider){
var vm = this;
$http({
url:”...”,
method: “get”,
params:{id:$stateparams.id}
}).then(function(response){
vm.student = student.data;
})
})
$ui-router Parameters
$ui-router Case-insensitive
To make ui-router case insensitive inject
$urlMatcherProvider() service into the config()
function and call caseInsensitive(true) function.
var app = angular
.module(“myModule”,[‘ui-router’])
.config(funtion($stateProvider,$urlMatcherPro
vider){
$urlMatcherProvider.caseInsentive(true);
});
$ui-router Default route
To achieve this inject $urlRouterProvider service into
config() function & use otherwise function for passing the
default route
var app = angular
.module(“myModule”,[‘ui-router’])
.config(funtion($stateProvider,$urlMatcherProvider,url
RouteProvider){
$urlRouterProvider.otherwise(“/home”);
});
$ui-router – Active menu item
Create a CSS in .css file or style tag
.activeClass{
background-color : pink;
}
Mention “ui-sref-active” directive in anchor tag
<a ui-sref=“home” ui-sref-active=“activeClass”>
Home
</a>
NESTED VIEWS & STATES
One of the benefit over ui-router with ng-route is,
ui-router provides & supports nested states &
views.
In nested states, there is parent-child relation i.e.,
the parent properties are available in all the child
states.
HOW TO SPECIFY
Can be specify in two ways
1. Using dot notation
.state(“home”,{
-----
})
.state(“home.list”,{
---
})
2. Using the parent property with the parent name as string.
.state{“home”,{
---
})
.state(“list”{
parent: “home”,
---
})
Initially my home page is displaying some text along with two buttons.
Which the buttons are activate the home page along with the activated
button data will be displayed.
RESULT
MULTIPLE NAMED VIEWS
Another benefit of ui-router is it supports multiple name
views.
If we define view object state's templateUrl, template and
templateProvider will be ignored i.e., Views override
state's template properties: that means we create
abstract states.
So in the case that you need a parent layout of these
views, you can define an abstract state that contains a
template, and a child state under the layout state that
contains the 'views' object.
CREATE NAMED VIEWS
$ui-router MULTIPLE VIEWS
UI-Router assigns every view to an absolute name. The
structure for this is viewName@stateName.
Since our main ui-view inside our about state, we gave it a
blank name.
The other two views
columnOne@about and columnTwo@about having the
naming scheme this way let’s us define multiple views
inside a single state.
RESULT
Angular Js Get Started - Complete Course

More Related Content

What's hot

Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJSDavid Parsons
 
Angular js 1.3 presentation for fed nov 2014
Angular js 1.3 presentation for fed   nov 2014Angular js 1.3 presentation for fed   nov 2014
Angular js 1.3 presentation for fed nov 2014Sarah Hudson
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introductionLuigi De Russis
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSSimon Guest
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JSBipin
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation Phan Tuan
 
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 startedStéphane Bégaudeau
 
AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)Gary Arora
 
Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework Sakthi Bro
 
Introduction of angular js
Introduction of angular jsIntroduction of angular js
Introduction of angular jsTamer Solieman
 

What's hot (20)

Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Angular js 1.3 presentation for fed nov 2014
Angular js 1.3 presentation for fed   nov 2014Angular js 1.3 presentation for fed   nov 2014
Angular js 1.3 presentation for fed nov 2014
 
AngularJS Best Practices
AngularJS Best PracticesAngularJS Best Practices
AngularJS Best Practices
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
AngularJS
AngularJSAngularJS
AngularJS
 
Angular js
Angular jsAngular js
Angular js
 
Angular js
Angular jsAngular js
Angular js
 
Angular js 1.3 basic tutorial
Angular js 1.3 basic tutorialAngular js 1.3 basic tutorial
Angular js 1.3 basic tutorial
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
 
Angular js
Angular jsAngular js
Angular js
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JS
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
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
 
Angular js
Angular jsAngular js
Angular js
 
AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)
 
Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework
 
Introduction of angular js
Introduction of angular jsIntroduction of angular js
Introduction of angular js
 
Angularjs PPT
Angularjs PPTAngularjs PPT
Angularjs PPT
 

Similar to Angular Js Get Started - Complete Course

introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basicsRavindra K
 
Intoduction to Angularjs
Intoduction to AngularjsIntoduction to Angularjs
Intoduction to AngularjsGaurav Agrawal
 
Angular js interview question answer for fresher
Angular js interview question answer for fresherAngular js interview question answer for fresher
Angular js interview question answer for fresherRavi Bhadauria
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosLearnimtactics
 
One Weekend With AngularJS
One Weekend With AngularJSOne Weekend With AngularJS
One Weekend With AngularJSYashobanta Bai
 
The Basics Angular JS
The Basics Angular JS The Basics Angular JS
The Basics Angular JS OrisysIndia
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014Ran Wahle
 
Angular workshop - Full Development Guide
Angular workshop - Full Development GuideAngular workshop - Full Development Guide
Angular workshop - Full Development GuideNitin Giri
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS BasicsRavi Mone
 
Introduction to AngularJS By Bharat Makwana
Introduction to AngularJS By Bharat MakwanaIntroduction to AngularJS By Bharat Makwana
Introduction to AngularJS By Bharat MakwanaBharat Makwana
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSmurtazahaveliwala
 
Leveling up with AngularJS
Leveling up with AngularJSLeveling up with AngularJS
Leveling up with AngularJSAustin Condiff
 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarAppfinz Technologies
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs WorkshopRan Wahle
 

Similar to Angular Js Get Started - Complete Course (20)

introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
 
Intoduction to Angularjs
Intoduction to AngularjsIntoduction to Angularjs
Intoduction to Angularjs
 
Angular js interview question answer for fresher
Angular js interview question answer for fresherAngular js interview question answer for fresher
Angular js interview question answer for fresher
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
 
One Weekend With AngularJS
One Weekend With AngularJSOne Weekend With AngularJS
One Weekend With AngularJS
 
Starting with angular js
Starting with angular js Starting with angular js
Starting with angular js
 
The Basics Angular JS
The Basics Angular JS The Basics Angular JS
The Basics Angular JS
 
AngularJS
AngularJSAngularJS
AngularJS
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
AngularJS By Vipin
AngularJS By VipinAngularJS By Vipin
AngularJS By Vipin
 
Angular workshop - Full Development Guide
Angular workshop - Full Development GuideAngular workshop - Full Development Guide
Angular workshop - Full Development Guide
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS Basics
 
Introduction to AngularJS By Bharat Makwana
Introduction to AngularJS By Bharat MakwanaIntroduction to AngularJS By Bharat Makwana
Introduction to AngularJS By Bharat Makwana
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
 
Leveling up with AngularJS
Leveling up with AngularJSLeveling up with AngularJS
Leveling up with AngularJS
 
Introduction to Angular Js
Introduction to Angular JsIntroduction to Angular Js
Introduction to Angular Js
 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumar
 
Angular js
Angular jsAngular js
Angular js
 
Angular js
Angular jsAngular js
Angular js
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
 

More from EPAM Systems

Complete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptComplete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptEPAM Systems
 
Css Complete Notes
Css Complete NotesCss Complete Notes
Css Complete NotesEPAM Systems
 
Css3 Complete Reference
Css3 Complete ReferenceCss3 Complete Reference
Css3 Complete ReferenceEPAM Systems
 
HTML 5 Complete Reference
HTML 5 Complete ReferenceHTML 5 Complete Reference
HTML 5 Complete ReferenceEPAM Systems
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsEPAM Systems
 
Bootstrap PPT Part - 2
Bootstrap PPT Part - 2Bootstrap PPT Part - 2
Bootstrap PPT Part - 2EPAM Systems
 
Bootstrap Part - 1
Bootstrap Part - 1Bootstrap Part - 1
Bootstrap Part - 1EPAM Systems
 

More from EPAM Systems (9)

Complete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptComplete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScript
 
Css Complete Notes
Css Complete NotesCss Complete Notes
Css Complete Notes
 
Css3 Complete Reference
Css3 Complete ReferenceCss3 Complete Reference
Css3 Complete Reference
 
Bootstrap 4 ppt
Bootstrap 4 pptBootstrap 4 ppt
Bootstrap 4 ppt
 
HTML 5 Complete Reference
HTML 5 Complete ReferenceHTML 5 Complete Reference
HTML 5 Complete Reference
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
 
Bootstrap PPT Part - 2
Bootstrap PPT Part - 2Bootstrap PPT Part - 2
Bootstrap PPT Part - 2
 
Bootstrap Part - 1
Bootstrap Part - 1Bootstrap Part - 1
Bootstrap Part - 1
 
Html
HtmlHtml
Html
 

Recently uploaded

Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 

Recently uploaded (20)

Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 

Angular Js Get Started - Complete Course

  • 2. INTRODUCTION Angular JS is a JavaScript framework you can use to build applications, but run in a web browser using HTML. The Angular JS framework started as a project inside of Google, but it's now an open source project so anyone can contribute to Angular or use Angular in their own applications.
  • 3. BENEFITS Used for Single page and line of pages of application Dependency Injection Two-way binding Testing MVC Controlling the DOM elements like Directives, Filters, Services, Controllers,…
  • 4. ANGULARJS.ORG – HOME FOR ANGULAR angularjs.org - this is where you can find links to mailing lists, find the documentation, find a Download button if you want to bring all of the Angular libraries down and use them locally, and there's also a link to GitHub where the raw source code lives. A related website you might be interested in is, builtwith.angularjs.org. This website includes pictures and links to other public websites that have been built with AngularJS.
  • 5. AN ANGULAR APPLICATION There are only two requirements for adding Angular JS to a web page <script> tag pointing to angular.js. need to add an ng-app attribute somewhere in your HTML ng-app, in Angular terminology, is called a directive, and it is just one of many directives that Angular provides. The ng prefix is short for Angular.
  • 7. EXAMPLE Angular found that particular binding expression, that's what we call it, and an output into the web page. The double curly braces are what some people would call mustaches or handlebars, they are binding expressions in Angular.  {{ expression }} – binding expression ng-init – initializes the application in the current scope.
  • 8. <!DOCTYPE html> <html> <head> <title>Angular JS - Arrays(StringS)</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></scri pt> </head> <body> <div ng-app="" ng-init="program=['HML','CSS','Jquery','AngularJs']"> <div ng-app="" ng-init="number=[5,25,50,75,100]"> <p> This is fist program:<span ng-bind="program[3]"></span><br> This is last program:<span ng-bind="program[1]"></span> </p> <p>Single quotes to be mentioned for sring values in the array declaration</p> </div> </body> </html>
  • 9. MODULE Modules are the basic building block of Angular. Everything exists inside of our module. A module is a container for different parts of your application i.e., controller, services, directives, filters etc.. Specifies the bootstrapping
  • 10. SYNTAX var myApp = angular.module(“myModule”,[]); myModule = name of our Module Empty square braces [] = dependents of our module
  • 11. EXAMPLE var myApp = angular.module('myModule', []); <!DOCTYPE html> <html ng-app = "myModule"> <head> <script data-require="angularjs@1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"> </script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body > <h1>Hello Plunker!</h1> {{ 8/4}} </body> </html>
  • 12. CONTROLLER The job of a controller is To build a model for View. It does by attaching to the $scope object. $scope is not a model it’s the data that we attach to $scope is the model.
  • 13. CREATING A CONTROLLER ng-controller is an attribute that we place into our HTML, we can specify the name of a controller that we want to take control of some area of the HTML Angular will invoke the controller function when it needs to create a controller to manage an area of the webpage. $scope is a component provided by Angular. What we can do with the scope argument is assign our model to the object.
  • 14. EXAMPLE var myApp = angular.module('myModule', []); myApp.controller('myController', function($scope) { $scope.message = "Hello Angular"; });
  • 15. <!DOCTYPE html> <html ng-app="myModule"> <head> <script data-require="angularjs@1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"> </script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body> <h1>Hello Plunker!</h1> {{ 8/4}} <br> <div ng-controller="myController"> {{message}} </div> </body> </html>
  • 16. EXAMPLE Now we've seen a controller in action, and we see that the primary responsibility of a controller is to set up the model on our $scope object. Angular passes $scope to our controller function, and our controller manipulates that scope. It only manipulates $scope by attaching a model. And then we use binding expressions to move data from the $scope into the view.
  • 17. EXAMPLE ///<refereence path="angular.min.js"/> var myApp=angular.module("myModule",[ ]); myApp.controller("myController", function($scope) { var employee = { firstName: "Avinash Kumar", lastName: "Gaddamanugu", gender: "Male“ }; $scope.employee=employee; });
  • 18. <!DOCTYPE html> <html ng-app="myModule"> <head> <title>Complex ng-model</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angula r.min.js"></script> <script src="angular.js"></script> <script type="text/javascript" src="ComplexScripts.js"></script> </head> <body> <div ng-controller="myController"> <div> First Name: {{ employee.firstName }} </div> <div> Last Name: {{ employee.lastName }} </div> <div> Gender: {{ employee.gender }} </div> </div> </body> </html>
  • 20. DIRECTIVES Controls the DOM elements (behavior) It is prefixed by ng. Eg: ng-init, ng-app, ng-model, ng-repeat The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
  • 21. NG-SRC The purpose of the ng-source directive is that once Angular is up and running, once it has evaluated this expression, then it will come in and set the actual source attribute for that image and the image should be successfully downloaded and you'll avoid these 404 errors. So ng-source is just a directive to set the source of an image when there's a data binding expression involved.
  • 22. TWO-WAY BINDING Keeps the model and the view sync all the time. Change in model updates the view and change in view updates the model. Model View Change in View updates View Change in View updates Model
  • 23. NG-MODEL Bind the value of an input field to a variable created in Angular JS Ng-model - always keep your data in sync It can be apply to inputs, select and textarea Example Ng-model.html, ng-model.js Also can specify in complex way Complex Module & Controller.html & Complex ng- model.js
  • 24. NG-MODEL CAN PROVIDE TYPE VALIDATION FOR APPLICATION DATA (NUMBER, E-MAIL, REQUIRED). <!DOCTYPE html > <html ng-app="" > <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js "></script> <body> <form name="myForm"> Email: <input type="email" name="myAddress" ng-model="text"> <span ng-show="myForm.myAddress.$error.email">Not a valid e- mail address</span> </form> <p>Enter your e-mail address in the input field. AngularJS will display an errormessage if the address is not an e-mail.</p> </body> </html>
  • 25. NG-MODEL DIRECTIVE CAN PROVIDE STATUS FOR APPLICATION DATA (INVALID, DIRTY, TOUCHED, ERROR) <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> <form ng-app="" name="myForm" ng-init="myText = 'post@myweb.com'"> Email: <input type="email" name="myAddress" ng-model="myText" required> <p>Edit the e-mail address, and try to change the status.</p> <h1>Status</h1> <p>Valid: {{myForm.myAddress.$valid}} (if true, the value meets all criteria).</p> <p>Dirty: {{myForm.myAddress.$dirty}} (if true, the value has been changed).</p> <p>Touched: {{myForm.myAddress.$touched}} (if true, the field has been in focus).</p> </form> </body></html>
  • 26. NG-MODEL DIRECTIVE PROVIDES CSS CLASSES FOR HTML ELEMENTS, DEPENDING ON THEIR STATUS ng-model directive adds/removes the following classes, according to the status of the form field ng-empty ng-not-empty ng-touched ng-untouched ng-valid ng-invalid ng-dirty ng-pending ng-pristine
  • 27. NG-REPEAT Similar to foreach() loop in C#. Table format Ng-repeat.html & ng-repeat.js List Format Ul-ng-repeat.html & ul-ng-repeat.js
  • 28. NG-OPTIONS Used for filling a dropdown list with options. Selected value to be an object For key-value pair Using an object as the data source, x represents the key, and y represents the value: <select ng-model="selectedCar" ng-options="x for (x, y) in cars"> </select> The selected value will always be the value in a key-value pair. The options in the dropdown list does not have to be the key in a key-value pair, it can also be the value, or a property of the value object <select ng-model="selectedCar" ng-options="y.brand for (x, y) in cars"> </select>
  • 29. NG-OPTIONS VS NG-REPEAT The ng-options directive was made especially for filling a dropdown list with options. The ng-repeat directive repeats a block of HTML code for each item in an array, it can be used to create options in a dropdown list. Dropdowns made with ng-options allows the selected value to be an object, while dropdowns made from ng-repeat has to be a string.
  • 30. NG-OPTIONS VS NG-REPEAT <select ng-model="selectedCar"> <option ng-repeat="x in cars" value="{{x.model}}">{{x.model}}</option> </select> <select ng-model="selectedCar" ng-options="x.model for x in cars"></select>
  • 31. CUSTOM DIRECTIVES Create New Directives In addition to all the built-in AngularJS directives, you can create your own directives. New directives are created by using the .directive function. To invoke the new directive, make an HTML element with the same tag name as the new directive. When naming a directive, you must use a camel case name, w3TestDirective, but when invoking it, you must use -separated name, w3-test-directive
  • 32. EXAMPLE<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"> </script> <body ng-app="myApp"> <w3-test-directive></w3-test-directive> <script> var app = angular.module("myApp", []); app.directive("w3TestDirective", function() { return { template : "<h1>Made by a directive!</h1>" }; }); </script> </body> </html>
  • 33. CUSTOM DIRECTIVE You can invoke a directive by using: Element name <w3-test-directive></w3-test-directive> Attribute <div w3-test-directive></div> Class <div class="w3-test-directive"></div> Comment <!-- directive: w3-test-directive --> You must add the value "C" to the restrict property to be able to invoke the directive from a class name.
  • 34. RESTRICTIONS Restrict your directives to only be invoked by some of the methods The legal restrict values are: E for Element name A for Attribute C for Class M for Comment By default the value is EA, meaning that both Element names and attribute names can invoke the directive.
  • 35. EVENT HANDLING – NG-CLICK An expression that’s going to be a function call Example Events.html & events.js
  • 36. In addition to these built-in directives, angular allows you to write custom directives. Custom directives to perform activities like drag-and-drop, or custom directives that can wrap bootstrap widgets, or media players, or wrappers for google maps.
  • 37. FILTERS Used to transform data Can do 3 different things Format data Sort data Filter data Can be used with a binding expression or a directive. To apply a filter use pipe (|) character {{ expression | filter : parameter }}
  • 38.
  • 39. DATE YYYY - 4 digit year – Ex: 1992 YY - 2 digit year –Ex: 1992:-92 MMMM – Full name (January – December) MMM – Jan – Dec MM – 01-12 M – Numerical Formats (1-12 ) (No leading zeros) dd – 01 -31 d – 1 – 31 (No leading zeros)
  • 40. THE FILTER FILTER The Filter filter selects a subset of an array. The Filter filter can only be used on arrays, and it returns an array containing only the matching item.
  • 41. LimitTo Filter limitTo filter: Can be used to limit the number of rows or characters in a string. {{ expression | limitTo : limit : begin }}
  • 42. ADDING FILTERS TO DIRECTIVES Filters are added to directives, like ng-repeat, by using the pipe character |, followed by a filter. <div ng-app="myApp" ng-controller="namesCtrl"> <ul> <li ng-repeat="x in names | orderBy:'country'"> {{ x.name + ', ' + x.country }} </li> </ul> </div>
  • 43. SORTING ROWS IN A TABLE tablesorting.html tablesorting.js
  • 44. SORTING BY MULTIPLE PROPERTIES Sortingdata.html Sortingdata.js Multiplesort.html Multiplesort.js
  • 47. ng-hide & ng-show Used to control the visibility of the HTML element. Hide Salary: <input type="checkbox" name="checkbox" ng-model="hideSalary" /> <thead> <tr> <th>Name</th> <th>Gender</th> <th>City</th> <th ng-hide="hideSalary">Salary</th> </tr> </thead> <tbody> <tr ng-repeat="emp in employees"> <td> {{ emp.name }} </td> <td> {{ emp.gender }} </td> <td> {{ emp.city }} </td> <td ng-hide="hideSalary"> {{ emp.salary }} </td> </tr> </tbody>
  • 48. ng-hide & ng-show <thead> <tr> <th>Name</th> <th>Gender</th> <th>City</th> <th ng-hide="hideSalary">Salary</th> <th ng-show="hideSalary">Salary</th> </tr> </thead> <tbody> <tr ng-repeat="emp in employees"> <td> {{ emp.name }} </td> <td> {{ emp.gender }} </td> <td> {{ emp.city }} </td> <td ng-hide="hideSalary"> {{ emp.salary }} </td> <th ng-show="hideSalary">####</th> </tr> </tbody>
  • 49. ng-include Used to embed an HTML page into another HTML page. Used when we want specific view in multiple pages of our application The value of the ng-include can be The name of HTML page that to be reusable A property on the $scope object that points to the reusable HTML page.
  • 50. SERVICE Is a an object that can be reused within an application. Eg: Math()- provides services to add number A service in angular is an object that provides some sort service that can be reused in a angular application. Angular JS has about 30 built-in services.
  • 51. NEED OF SERVICE Single Responsibility Condition: States that an object should have a single responsibility. Services encapsulate reusable logic that doesn’t belong anywhere else (i.e., directives, filters, views, model & controller) Benefits Reusability Eg: $http Dependency Injection Testability
  • 52. $location Service return information about the location of the current web page <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="myCtrl"> <p>The url of this page is:</p> <h3>{{myUrl}}</h3> </div> <p>This example uses the built-in $location service to get the absolute url of the page.</p> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $location) { $scope.myUrl = $location.absUrl(); }); </script>
  • 53. $interval Service <body> <div ng-app="myApp" ng-controller="myCtrl"> <p>The time is:</p> <h1>{{theTime}}</h1> </div> <p>The $interval service runs a function every specified millisecond.</p> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $interval) { $scope.theTime = new Date().toLocaleTimeString(); $interval(function () { $scope.theTime = new Date().toLocaleTimeString(); }, 1000); }); </script> </body>
  • 54. $timeout Service <body> <div ng-app="myApp" ng-controller="myCtrl"> <p>This header will change after two seconds:</p> <h1>{{myHeader}}</h1> </div> <p>The $timeout service runs a function after a sepecified number of milliseconds.</p> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $timeout) { $scope.myHeader = "Hello World!"; $timeout(function () { $scope.myHeader = "How are you today?";}, 2000); }); </script>
  • 55. $http Service <div ng-app="myApp" ng-controller="empController"> <table> <tr><th>Name</th></tr> <tr ng-repeat=“emp in empployees”> <td>{{emp.name}}</td> </tr> </table> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $http ,$log) { $http.get(“data.json)then(function (response) { $scope.employees = response.data; }); }); </script>
  • 56. PROMISE OBJECT $http service returns a promise object as the functions are executed asynchronously. A promise object is an object that promises to give you some result in the future, and that result might be the data that you need, or the result might be an error if the server was unavailable. The way I find out is to call a then() method on my promise and pass the then() method a function that will be called in the future.
  • 57. EG: PROMISE OBJECT var myApp=angular.module(“serviceApp”,[]) .controller(“serviceCtrl”,function($scope, $http){ $http.get(‘sample.html’) .then(function(scope) { $scope.myWelcome = response.data; }); }); Function is called when the request completed successfully, we get response from the server Ex: http://andyshora.com/promises-angularjs-explained-as-cartoon.html
  • 58. CUSTOM SERVICES An AngularJS service can be created or registered or created in four different ways, Using the service() method Using the factory() method Using the provider() method Using the value() method Using the constant() method
  • 59. service() vs factory() Using the service() method uses the function constructor and it returns the object or instance of the function to work with. Using the factory() method uses the returned value of the function. It returns the value of the function returned after the execution
  • 60. NORMAL SERVICE var myApp = angular.module("myModule", []) .controller("myController", function($scope){ $scope.transformString = function(input){ if(!input) { return input; } var output = ""; for (var i = 0; i < input.length; i++) { if(i>0 && input[i] == input[i].toUpperCase()) { output = output + " "; } output = output + input[i]; } $scope.output = output; } });
  • 61. NORMAL SERVICE CALL In this we have two problems The controller code become complex and large If we want to reuse this code in any controller we have to duplicate that code within that controller. At the moment we start duplicating the maintainability of the application will be loss. To overcome this we encapsulate the service and inject that service into any controller where we want to use.
  • 62. SERVICE/FACTORY METHOD It is used for creating the custom service and register this with angular. myApp.factory(‘stringService’, function(){ return { processingString: function(input){ ------ ---- } }; )}
  • 63. SYNTAX var myApp = angular.module(“myModule”,[]) .controller(“myCtrl”,function($scope, stringService) { $scope.transformString = function(input) { $scope.out = stringService.processingString(input); } });
  • 64. $http get() In Angularjs get ($http.get()) service or method is used to get data from remote HTTP servers. var app = angular.module('getserviceApp', []); app.controller('getserviceCtrl', function ($scope, $http) { // Simple GET request example: $http({ method: 'GET', url: '/sampleUrl', data: 'parameters' }) .then(function success(response) { // this function will be called when the request is success }, function error(response) { // this function will be called when the request returned error status }); });
  • 65. SYNTAX method - This property is used to define required operator like get or send data. In angularjs we have different methods available. url - We need to send url of http server to perform required operations. data - If we have any parameters to send and get data from request url we will pass it using this parameter. then - In then property we will do our coding based on response status either success or failure. If it is success it will execute first method or in case if we get error second method will execute.
  • 66. $http.get Properties config - The configuration object is used to generate the request. data - It’s string or an object which is used to carry response from the server. headers - This function is used to get header information. status - This property is used to get HTTP status code of the response. statusText - This property is used to get HTTP status text of the response.
  • 67. $http post() method The $http.POST() services are used to send the data to a specific URL and expects the resource at that URL to handle the request that means we can say that POST method is used to Insert new data based on given URL
  • 68. SYNTAX var app = angular.module('putserviceApp', []); app.controller('putserviceCtrl', function ($scope, $http) { // Simple Post request example: var url = 'posturl', data = 'parameters',config='contenttype'; $http.post(url, data, config) .then(function (response) { // This function handles success }, function (response) { // this function handles error }); });
  • 69. $http.post() Properties config - The configuration object is used to generate the request. data - It’s either string or an object. headers - We can get header information. status - We can get HTTP status code of the response. statusText - Get HTTP status text of the response.
  • 70. $http.put() method The $http.put() service in angularjs is used to upload a files to server and update existing data in server based on given URL. Generally $http.put method not allowed by many servers due to security reasons.
  • 71. SYNTAX var app = angular.module('putserviceApp', []); app.controller('putserviceCtrl', function ($scope, $http) { // Simple Put request example: var url = 'puturl', data = 'parameters',config='contenttype'; $http.put(url, data, config).then(function (response) { // This function handles success }, function (response) { // this function handles error }); });
  • 72. SYNTAX url - Used to send url of http server to perform required operations. data - This property to send required parameters to requested url. config - By using this property we can change content-type. After execution of our $http.put request we will get response based on that response status our success and failure methods will execut
  • 73. $http put() Properties config - The configuration object is used to generate the request. data - It’s either string or an object. headers - We can get header information. status - We can get HTTP status code of the response. statusText - Get HTTP status text of the response.
  • 74. $http.jsonp() Service In angularjs jsonp or json with padding service is used to make cross domain requests from client browser. By using $http.jsonp service in angularjs we can get data in json format and the server whatever we are requesting should support jsonp requests otherwise it’s worthless
  • 75. BENEFIT Generally now a days browsers are blocking access data from a server which is in different domain due to same origin policy. By using angularjs $http.jsonp method we can access data from different domain without having any access problems.
  • 76. SYNTAX var app = angular.module('jsonserviceApp', []); app.controller('jsonCtrl', function ($scope, $http) { //Call the service to get data in json var url = "Some API Url" + "?callback=JSON_CALLBACK"; $http.jsonp(url) .success(function (data, status, headers, config) { $scope.details = data; }) .error(function (data, status, headers, config) { $scope.statusval = status; }); });
  • 77. JSON_CALLBACK “callback=JSON_CALLBACK” to url to make a service request. AngularJs is having its own callback pattern, so it will follow that pattern to handle jsonp callbacks. In angularjs always we need to send callback=JSON_CALLBACK with url while requesting jsonp service. Using this pattern we handle the JSONP call-back and its call-back is called JSON_CALLBACK.
  • 78. Angularjs Success / Error Functions In angularjs while using $http services we have success() and error() functions with then property to display the success and failed response of request information. In angularjs we can use success and error methods with http GET, POST, PUT, DELETE, JSONP and PATCH services.
  • 79. SYNTAX var app = angular.module('getserviceApp', []); app.controller('getserviceCtrl', function ($scope, $http) { // Simple GET request example: $http.get("url").then(function success(response) { // this function will be called when the request is success }, function error(response) { // this function will be called when the request returned error status }); });
  • 80. anchorScroll Used to jump to specified element on the page. var myApp=angular.module("myModule",[ ]); myApp.controller("myController", function($scope, $location, $anchorScroll) { $scope.scrollTo = function(scrollLocation) //mention the id of the element { $location.hash(scrollLocation); $anchorScroll(); } });
  • 81. CLIENT AND SERVER ROUTING Server-Side routing: A client would request a webpage or other resource from the server using a URL and the server retrieves the resource and sends it back to the client. Often this meant that an entire webpage would be sent back to the browser after each request to the server.
  • 82. CLIENT – SIDE ROUTING Client – Side Routing However, when using a client-side framework like Angular, the requests to the server are of often for smaller bits of information rather than entire webpages and all of their related resources. Client-side routing doesn't replace server-side routing. All web applications still interact heavily with servers and those servers still need to accept a URL and use it to locate and return the resource needed by the client.
  • 83. SERVER-SIDE ROUTING WITH SPAS AND CLIENT-SIDE ROUTING. SPA stands for Single Page Application. The idea behind a SPA is that it appears to the user as if it's one page in the browser and you only update portions of that page as the user interacts with the application.
  • 84.
  • 85. ngRoute ngRoute is its own Angular module, and stored in its own JavaScript file. ngRoute module helps your application to become a Single Page Application. The ngRoute module routes your application to different pages without reloading the entire application.
  • 86.
  • 87. WHAT DO I NEED To make your applications ready for routing, you must include the AngularJS Route module: <script src="https://ajax.googleapis.com/ajax/libs/angul arjs/1.4.8/angular-route.js"></script> Then you must add the ngRoute as a dependency in the application module:: var app = angular.module("myApp", ["ngRoute"]);
  • 88. $routeProvider Define the $routeProvider using the config method of application. Work registered in the config method will be performed when the application is loading. ngRoute – provides the routing this our dependency $ routeProvider – used to configure routes
  • 89. $routeProvider to configure routes app.config(function($routeProvider) { $routeProvider .when("/", { templateUrl : "main.htm" }) .when("/red", { templateUrl : "red.htm" }) .when("/green", { templateUrl : "green.htm" }) .when("/blue", { templateUrl : "blue.htm" }); });
  • 91. WHERE DOES IT GO? Application needs a container to put the content provided by the routing. This container is the ng-view directive. There are three different ways to include the ng- view directive in your application <div ng-view></div> as attribute <ng-view></ng-view> as tag <div class="ng-view"></div> as class
  • 92. USING CONTROLLERS With the $routeProvider you can also define a controller for each "view". var app = angular.module("myApp", ["ngRoute"]); app.config(function($routeProvider) { $routeProvider .when("/", { templateUrl : "main.htm" }) .when("/london", { templateUrl : "london.htm", controller : "londonCtrl" }) .when("/paris", { templateUrl : "paris.htm", controller : "parisCtrl" }); }); app.controller("londonCtrl", function ($scope) { $scope.msg = "I love London"; }); app.controller("parisCtrl", function ($scope) { $scope.msg = "I love Paris"; });
  • 93. otherwise() otherwise method, is the default route when none of the others get a match If you try to navigate to route that is not configured, any partial template will not be injected because angular doesn’t know the route of template/site. .otherwise({ redierctTo : “/main”; })
  • 94. INLINE TEMPLATE The template property, allows you to write HTML directly in the property value, and not refer to a page. Eg: var app = angular.module("myApp", ["ngRoute"]); app.config(function($routeProvider) { $routeProvider .when("/", { template : "<h1>Main</h1><p>Click on the links to change this content</p>" }); })
  • 95. $route Service It has two methods, reload and updateParams The updateParams method allows you to reload the current URL with a new set of route parameters. You pass the new parameters as properties on an object to the updateParams method. The property names that match parameter names you've configured on the route, will then have the new values inserted into the URL. The reload method will reload the current route. This will simply reload the current route within your Angular app, which mean it will make any necessary network calls, process route parameters, and generally treat the route as if you were visiting it for the first time.
  • 96. $route Service - Parameters The current property : gives you a reference to the current route definition and allows you to exam the controller for the route, scope, and other variables used when creating the route's controller. The routes property : is an object containing all of the route definitions for your application. You can use it to see all of the routes you've configured on the route provider.
  • 97.
  • 98.
  • 99. reload() By using the reload() function on the route service give us the ability to refresh the data on the home page of the app. .controller(“homeController, function($http,$route) var vm = this; vm. reloadData = function() { route.reloadData(); }
  • 100. Route change This is used when we are filling long form application. This is created with a alert window asking for OK and Cancel OK: navigate to next partial template/page Cancel: stays in current page
  • 101. Route Change When a route change occurs, then two events are generated $routeChangeStart $locationChangeStart The only difference between two events is the ‘next’ and ‘current’ parameters. The $locationChangeStart event ‘next’ and ‘current’ parameters has got complete next and current URL’s
  • 103. NAVIGATION PAGE We can also specify to which page we are navigating. .controller(“studentController”, function($http,$scope,$route) $route.$on(“$routeChangeStart”, function(event,next,current) { if(!confirm(“Are you sure to navigate” + next.$$route.orginalPath)) { event.preventDefault(); } }
  • 105. NAVIGATION PAGE We can also specify to which page we are navigating. .controller(“studentController”,function($http,$scope,$route) $route.$on(“$locationChangeStart”, function(event,next,current) { if(!confirm(“Are you sure to navigate” + next)) { event.preventDefault(); } }
  • 106. ROUTE RESOLVE If the components of the application i.e., database server, application and the client present in different machines and a network latency then the data few seconds to load. If the components of the application are in local machine, then there will not be any network latency.
  • 107.
  • 108.
  • 109. REMOVE (#) SYMBOL Enable html5mode $locationProvider.html5mode(true); Remove # in anchor tag Include URL rewrite rule in web.config Set base href element to the location of single page application <base href=“/” /> all the partial templates are present within the root element
  • 110. ANGULAR CASE-INSENSITIVE By default Angular is case sensitive To make a route to case insensitive make it true. $routeProvider.caseInsensitiveMatch = true;
  • 111. CONTROLLER AS SYNTAX There is another mechanism to make the members of the controller available in the view i.e., Controller As Syntax With this there is no need for injecting the $scope object. Instead we use ‘this’ keyword.
  • 112. <!DOCTYPE html> <html ng-app = “myModule”> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.m in.js"> </script> <script> var app = angular .module (“myModule”,[]) .controller (“myController”, function(){ this.message = “Angular JS Tutorial”; }); </script> <body ng-controller = “myController as myCtrl”> <h2> {{ myCtrl.message }} </h2> </body> </html>
  • 113. NESTED CONTROLLER <div ng-controller="countryController"> {{name}} <div ng-controller="stateController"> {{name}} <div ng-controller="cityController"> {name}} </div </div> </div>
  • 114. CONTROLLER vs SCOPE Controller as syntax is new & released 1.2.0 officially. $scope is the old technique & is available since the initial version of angular is released. Controller as syntax makes code more readable. If you want to use $scope object it is to be injected into the controller function, where as with controller as syntax there is no need for such injection, unless it is for some thing else.
  • 115. $scope var myApp=angular.module("myModule",[]) .controller("countryController", function($scope){ $scope.name = "India"; }); Controller as syntax var myApp=angular.module("myModule",[]) .controller("countryController", function(){ this.name = "India"; });
  • 116. CONTROLLER vs SCOPE Though we are using controller as syntax; don’t think that angular won’t use $scope. It is using but it is hiding. That is in controller as syntax we aliasing the controller: myController as myCtrl This cityCtrl is reference variable pointing to the myController. Angular will take this reference and attach to the $scope object.
  • 117. $scope vs $rootscope $rootScope: Is available globally (for all controllers) $scope: Is available only to the controller that is created.
  • 118. var myApp = angular.module("myModule", []) .controller("redController", function($scope, $rootScope) { $scope.redColor = "I am Red"; $rootScope.rootScopeColor = "I am Root Scope Color"; }) .controller("greenController", function($scope) { $scope.greenColor ="I am Green"; })
  • 119. <body> <div ng-controller="redController"> Root Scope : {{ rootScopeColor }}<br> Red Color Controller : {{ redColor }}<br> Green Color Controller :{{ greenColor }} </div> <br> <div ng-controller="greenController"> Root Scope : {{rootScopeColor}}<br> Green Color Controller : {{greenColor}}<br> Red Color Controller :{{redColor}} </div> </body>
  • 120. Angular $ui-router The ui-router is a 3rd party routing framework for Angular JS ui-router implements routing based on the state of the application where as ngRoute implements routing based on the route URL.
  • 121. $ui-router vs ngroute ngRoute implements routing based on the route URL that means we use view & routes that are tied to the application URL. ui-router use the routes that are not tied to the application URL that means parts of the sites can be changed even if the URL doesn’t change.
  • 122. How to get $ui-router
  • 123. WHAT DO I NEED The first thing you need to do is reference the UI-Router JavaScript file. Get the CDN link from: https://cdnjs.com/libraries/angular-ui-router <script src=“https://cdnjs.cloudflare.com/ajax/libs/angular-ui- router/0.3.2/angular-ui-router.js”></script> (OR) <script src=“https://cdnjs.cloudflare.com/ajax/libs/angular-ui- router/0.3.2/angular-ui-router.min.js”></script>
  • 124. ADD A MODULE DEPENDENCY ON UI- ROUTER.
  • 125. $ui-view Directive Finally, you'll need to add a ui-view directive to your page. This is the rough equivalent of using the ngView directive when working with ngRoute. It gives the router a place to insert views into your page.
  • 127. CONFIGURING STATES Call the config function module, and inject into it the state $stateProvider service that comes with UI- Router. It has two parameters The first parameter to the function is the name you want to give the state. The second parameter to the state function is a configuration object.
  • 128. CONFIGURING STATES var myApp = angular.module(“myModule”,[‘ui-roter’]) .config(function($stateProvider){ $stateProvider .state(“home” { url: “/home”, templateUrl: “Templates/home.html”, controller: “homeController”, controllerAs: “homeCtrl” }) });
  • 129. Inline $ui-router var myApp = angular.module(“myModule”,[‘ui-roter’]) .config(function($stateProvider){ $stateProvider .state(“home” { url: “/home”, template: “Hello Angular”, controller: “homeController”, controllerAs: “homeCtrl” }) });
  • 130. $ui-router Parameters Define the sate with URL parameter .state(“studentDetails”,{ url:”/studentdetail/:id”, templateUrl:”Templates/studentDetails.html”, controller: “studentDetailsController”, controllerAs:”studentDetailsCtrl” })
  • 131. Link to the state with URL parameter <ul> <li ng-repeat=“studentDetailsCtrl.students”> <a ui-sref=“studentDetails({id:student,id})”></a> </li> </ul> $ui-router Parameters
  • 132. Read the specific parameter value from controller function, call the web-service method(if any) & id value & then retrieve that specific parameter.( Eg :student details) controller(“studentDetailsController”,function($scope,$stateProvider){ var vm = this; $http({ url:”...”, method: “get”, params:{id:$stateparams.id} }).then(function(response){ vm.student = student.data; }) }) $ui-router Parameters
  • 133. $ui-router Case-insensitive To make ui-router case insensitive inject $urlMatcherProvider() service into the config() function and call caseInsensitive(true) function. var app = angular .module(“myModule”,[‘ui-router’]) .config(funtion($stateProvider,$urlMatcherPro vider){ $urlMatcherProvider.caseInsentive(true); });
  • 134. $ui-router Default route To achieve this inject $urlRouterProvider service into config() function & use otherwise function for passing the default route var app = angular .module(“myModule”,[‘ui-router’]) .config(funtion($stateProvider,$urlMatcherProvider,url RouteProvider){ $urlRouterProvider.otherwise(“/home”); });
  • 135. $ui-router – Active menu item Create a CSS in .css file or style tag .activeClass{ background-color : pink; } Mention “ui-sref-active” directive in anchor tag <a ui-sref=“home” ui-sref-active=“activeClass”> Home </a>
  • 136. NESTED VIEWS & STATES One of the benefit over ui-router with ng-route is, ui-router provides & supports nested states & views. In nested states, there is parent-child relation i.e., the parent properties are available in all the child states.
  • 137. HOW TO SPECIFY Can be specify in two ways 1. Using dot notation .state(“home”,{ ----- }) .state(“home.list”,{ --- }) 2. Using the parent property with the parent name as string. .state{“home”,{ --- }) .state(“list”{ parent: “home”, --- })
  • 138.
  • 139. Initially my home page is displaying some text along with two buttons. Which the buttons are activate the home page along with the activated button data will be displayed.
  • 140. RESULT
  • 141. MULTIPLE NAMED VIEWS Another benefit of ui-router is it supports multiple name views. If we define view object state's templateUrl, template and templateProvider will be ignored i.e., Views override state's template properties: that means we create abstract states. So in the case that you need a parent layout of these views, you can define an abstract state that contains a template, and a child state under the layout state that contains the 'views' object.
  • 143.
  • 144. $ui-router MULTIPLE VIEWS UI-Router assigns every view to an absolute name. The structure for this is viewName@stateName. Since our main ui-view inside our about state, we gave it a blank name. The other two views columnOne@about and columnTwo@about having the naming scheme this way let’s us define multiple views inside a single state.
  • 145. RESULT

Editor's Notes

  1. Two-way binding – sync model and view. A change in model, update the view and vice-versa
  2. Angular.js is the only script file that you need for the core Angular features, because Angular has no other dependencies on other libraries. So whenever you see ng in your code or in documentation, or in a website name, or a bumper sticker, think Angular. ng-app is what we call the application directive. It is a special directive that Angular looks for inside of your HTML, and if it finds it, Angular will bootstrap itself; so it initializes itself and it jumps into action to start managing the page. Let's try this.
  3. My other requirement, though, is to add an ng-app directive somewhere in my markup. Some people like to add that directly to the html element; I could also add it somewhere else inside of the page, like on the body element, but you do only get one ng-app directive per page, and Angular's only going to take control of the section of DOM where that ng-app directive applies. So in this case it will apply to everything in the body; I won't be able to use Angular expressions and features outside of the body tag. But with the script in place and my ng-app directive in place,
  4. <div ng-app="" ng-init="quantity=1;cost=5"> <p>Total in dollar: {{ quantity * cost }}</p> <p>Total in dollar: {{ 4*2 }}</p> </div>
  5. Complex representation
  6. The first thing I need to do is create a module and give it a name. I do this with an Angular API, angular.module. Angular, that particular object, is the one single identifier that Angular puts into the global namespace, so I can use it anywhere where angular.js is included. And that Angular object has methods like, .module, that will allow me to create a module or get a reference to an existing module.
  7. This empty array tells Angular that our module does not depend on any other modules. Later on, we will add set of dependencies to our module. But for now it has done. The other thing we are doing is capturing that module into a global variable called. This will make it easy for us to create objects inside of this module, such as controllers and services.
  8. Example: script.js var myApp = angular.module('myModule', []); index.html <!DOCTYPE html> <html ng-app = "myModule"> <head> <script data-require="angularjs@1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"> </script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body > <h1>Hello Plunker!</h1> {{ 8/4}} </body> </html>
  9. 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. So it might need to make some calculations or call back to a web server that talks to a database, whatever it takes. I'll show you how to build a controller that is able to build a model.
  10. is a new directive, the ng-controller directive. ng-controller is an attribute that we place into our HTML. So just like ng-app is a directive, ng-controller is another directive. And when we use ng-controller, we can specify the name of a controller that we want to take control of some area of the HTML. So in this code snippet, ng-app will initialize Angular and Angular will take control of that div and everything inside of it. Inside of that div is a child div where we can put something called. ng-controller can only be used where we have an ng-app in place, and we have to tell Angular the name of the controller that will be in charge. You'll encounter a few things with dollar signs in the front when you work with Angular, and just like the ng prefix, the dollar sign prefix is a sign that the component you're working with is a component provided by Angular. What we can do with the scope argument is assign our model to the object. So $scope is not the model, but things that we attach to that $scope are going to be the model.
  11. 'myController’ = name of the controller function($scope) – anonymous function – manages the web page invoked by angular $scope - assign our model to the object Here we are passing the $scope as the parameter to this we attaching the message property. So here the scope is not the model, message property attached to scope is the model which is available in the view by binding expression the model from the scope. That is controller isn’t manipulating the DOM elements directly, it is showing the clean separation between the model, view and the controller.
  12. When the HTML renders, the browser is going to see "img src=" and then this binding expression. It's not until later when Angular is up and running, that it comes in and replaces person.imageSrc with the value from my model. But unfortunately, the way the browser works, as soon as it sees "<img src="{{person.imageSrc}}", it's going to go and try to download an image, treating that binding expression as a URL. And in fact, down inside of the Console window here, you can see that each time it refreshed the Preview window, it tried to grab that image and got a 404 error, could not be found.
  13. But for now just know that ng-model, an extremely useful directive because you can apply it to inputs, you can apply it to selects, you can apply it to text areas, and what ng-model will do is always keep your data in sync; it's going to move information that the user types into your model. And if for some reason the model changes, it will move that information back into your input.
  14. Formng-model.html
  15. Formstatusng-model
  16. Ng-modelclasses.html <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <style> input.ng-invalid { background-color: lightblue; } </style> <body> <form ng-app="" name="myForm"> Enter your name: <input name="myName" ng-model="myText" required> </form> <p>Edit the text field and it will get/lose classes according to the status.</p> <p><b>Note:</b> A text field with the "required" attribute is not valid when it is empty.</p>
  17. Eg1: ng-options-object.html Eg2: ng-options.html
  18. <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="myCtrl"> <select> <option ng-repeat="x in names">{{x}}</option> </select> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.names = ["Emil", "Tobias", "Linus"]; }); </script> <p>This example shows how to fill a dropdown list using the ng-repeat directive.</p> </body> </html>
  19. Eg: ng-repeat-ex.html Eg: ng-options-ex.html
  20. <w3TestDirective>
  21. Add restrict : "C",
  22. var app = angular.module("myApp", []); app.directive("w3TestDirective", function() {     return {         restrict : "A",         template : "<h1>Made by a directive!</h1>"     }; });
  23. Ex: filterUppercase.html (lowercase) Ex: filterCurrency.html
  24. Ex: filterFilter.html
  25. Filterdirective.html
  26. Primary need of controller is to create model to view. This should do more things. If it does, then it violets the single responsibility principle. Eg: If the controller having to compute a page with dob/math value along with building a model, then it violets one of its responsibility. This single responsibility logic is injected into external service, that need that services.
  27. Locationservice.html
  28. he $interval service is AngularJS' version of the window.setInterval function. The $interval service runs a function every specified millisecond.
  29. The $timeout service is AngularJS' version of the window.setTimeout function. The $timeout service runs a function after a sepecified number of milliseconds.
  30. The $http service is one of the most common used services in Angular JS applications. The service makes a request to the server, and lets your application handle the response. Ex: httpservice.html
  31. The way I find out is to call a then method on my promise and pass the then method a function that will be called in the future. The then method will call the function when the data is ready sometime in the future, and it will pass the data into the function as a parameter. $http service returns a promise object this means that the functions returns may not be available immediately because we can’t return value of the HTTP servers action.
  32. promiseobject.html & sample.html $http.get({ method: ‘GET’ url: ’ sample.html’ )} .then(function(scope) { $scope.employee = response.data; )};
  33. If we want to register a service using the function constructor, in that scenario we will use service() method to register the service. If we use factory() method to register the service it returns the value after execution of the service function. It can return any value like primitive value, function or object. So service() method returns the function object whereas factory() method can return any kind of value.
  34. Customeservice1.html Customservice1.js
  35. A factory() contains two parameters name of the factory method where we create a custom service and an anonymous function stringService: name of the factory method Function() returns a Java Script object ( a service in a angular is nothing but a JavaScript object with some special properties and functions). Usually a service in angular is stateless. Now all the logic is in stringService. We can call it by using the processingString method in any controller. Now we need to inject this into our controller function
  36. $httpget().html Sample.html
  37. url - We need to send url of http server to perform required operations. data - We will use this property to send required parameters to requested url. config - By using this property we can change content-type
  38. $httppost().html
  39. $httpput().html
  40. $httpjsonp.html
  41. The function in the we pass three parameters- $scope object, $location service (which specifies location of the current web page), $anchorScroll service $location service hash() appends the hash (#) fragment to the URL. $anchorScroll method reads the hash fragment in the URL & jumps to the element on the page. (automatically scrolls)
  42. It's really just a process of a server using a URL to locate some resource and returning it to the client. The URL specifies the route. Routes are basically locations. Prior to the explosion of JavaScript libraries and frameworks, most web applications were executed almost entirely on servers. A client would request a webpage or other resource from the server using a URL and the server retrieves the resource and sends it back to the client. Often this meant that an entire webpage would be sent back to the browser after each request to the server.
  43. Client-side routing doesn't replace server-side routing. All web applications still interact heavily with servers and those servers still need to accept a URL and use it to locate and return the resource needed by the client. However, when using a client-side framework like Angular, the requests to the server are of often for smaller bits of information rather than entire webpages and all of their related resources.
  44. Let's assume this is the home screen of our new single page Angular app. We've got a title at the top, a few links down the left side and some content in the middle. When the user takes some action like clicking the first link on the left, the application navigates them to a new client-side route and loads information related to that route into a portion of the page. When they click a second link, they may be taken to a new route which loads different information into the same part of the page. These route transitions will often retrieve resources from a server. That could include partial HTML files, JSON data, images or anything else you might normally request from a server. So using client-side routing does not mean that there is no interaction with the server or that the server isn't also locating and returning resources based on its own routes. It just means that the whole page in the browser is no longer being reloaded with every server interaction and that the client application needs a way to find and refer to various locations within the app.
  45. If you want to navigate to different pages in your application, but you also want the application to be a SPA (Single Page Application), with no page reloading, you can use the ngRoute module.
  46. First, you can install it with bower. Bower is a package manager primarily used for client side code. The command to install ngRoute is bower install angular-route, followed by the hash sign and the version you want. You can also use npm to install the file. Npm is the node package manager. It works similarly to bower. The command to install ngRoute with npm is npm install angular-route, followed by the at sign and the version number. You can simply add a JavaScript file reference to this URL, and you don't have to bother keeping up with the file in your project at all. The last technique I'll mention is to manually download the file and add it to your project. All the Angular code can be found on the code.angularjs.org website.
  47. Define the $routeProvider using the config method of your application. Work registered in the config method will be performed when the application is loading.
  48. Ex:routing.html
  49. Ex: mainroute.html
  50. Ex: Inlinerouting.html
  51. Finally, the route service has several events that fire at various points in the route transition process. You can handle these events using the on function that exists on the root scope.
  52. ngrouteparams.html Sample1.htm Sample2.htm
  53. Routeparams example
  54. When accidently we press a navigation link while filling application, then the unsaved data will be losed, To prevent this we will take confirmation message whether we want to navigate or not.
  55. Nestedcontroller.html Nestedcontroller.js
  56. Nestedcontroller.html Nestedcontroller.js
  57. Nestedcontroller.html Nestedcontroller.js
  58. rootScope.html rootScope.js
  59. Inlinetemplate.html
  60. the ui-sref we defined in home.html are linked to an actual state. With home.list and home.paragraph created, those links will now take the template provided and inject it into ui-view.
  61. The benefit of abstract state is the URL of the parent state is prepended to the URL of the child states, that means we can remove any redundant part from child state’s URL.