AngularJS W3schhols
AngularJS W3schhols
in
TIP
Press CTRL+B or CLICK Bookmarks in your PDF reader for easy navigation
Created By www.ebooktutorials.in
This tutorial is specially designed to help you learn AngularJS as quickly and
efficiently as possible.
First, you will learn the basics of AngularJS: directives, expressions, filters,
modules, and controllers.
Then you will learn everything else you need to know about AngularJS:
Events, DOM, Forms, Input, Validation, Http, and more.
Created By www.ebooktutorials.in
AngularJS Example
<!DOCTYPE html>
<html lang="en-US">
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.
js"></script>
<body>
<div ng-app="">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
</div>
</body>
</html>
HTML
CSS
JavaScript
AngularJS History
AngularJS version 1.0 was released in 2012.
Miko Hevery, a Google employee, started to work with AngularJS in 2009.
The idea turned out very well, and the project is now officially supported by
Google.
Created By www.ebooktutorials.in
AngularJS Example
<!DOCTYPE html>
<html>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.
js"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div></body></html>
Content Downloaded from www.w3schools.com
Created By www.ebooktutorials.in
Example explained:
AngularJS starts automatically when the web page has loaded.
The ng-app directive tells AngularJS that the <div> element is the "owner" of
an AngularJSapplication.
The ng-model directive binds the value of the input field to the application
variable name.
The ng-bind directive binds the innerHTML of the <p> element to the
application variablename.
As you have already seen, AngularJS directives are HTML attributes with
an ng prefix.
The ng-init directive initialize AngularJS application variables.
AngularJS Example
<div ng-app="" ng-init="firstName='John'">
<p>The name is <span ng-bind="firstName"></span></p>
</div>
AngularJS Example
<div data-ng-app="" data-ng-init="firstName='John'">
<p>The name is <span data-ng-bind="firstName"></span></p>
</div>
You can use data-ng-, instead of ng-, if you want to make your page
HTML valid.
You will learn a lot more about directives later in this tutorial.
Created By www.ebooktutorials.in
AngularJS Example
<!DOCTYPE html>
<html>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.
js"></script>
<body>
<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>
AngularJS expressions bind AngularJS data to HTML the same way as the ngbind directive.
AngularJS Example
<!DOCTYPE html>
<html>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.
js"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p>{{name}}</p>
</div>
</body>
</html>
Created By www.ebooktutorials.in
AngularJS Example
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
Created By www.ebooktutorials.in
Example
<!DOCTYPE html>
<html>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.
js"></script>
<body>
<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>
Created By www.ebooktutorials.in
If you remove the ng-app directive, HTML will display the expression as it is,
without solving it:
Example
<!DOCTYPE html>
<html>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.
js"></script>
<body>
<div>
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>
You can write expressions wherever you like, AngularJS will simply resolve the
expression and return the result.
Example: Let AngularJS change the value of CSS properties.
Change the color of the input box below, by changing it's value:
lightblue
Example
<div ng-app="" ng-init="myCol='lightblue'">
<input style="background-color:{{myCol}}" ng-model="myCol" value="{{myCol}}">
</div>
Example
<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div>
Created By www.ebooktutorials.in
Example
<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: <span ng-bind="quantity * cost"></span></p>
</div>
Using ng-init is not very common. You will learn a better way to
initialize data in the chapter about controllers.
Example
<div ng-app="" ng-init="firstName='John';lastName='Doe'">
<p>The name is {{ firstName + " " + lastName }}</p>
</div>
Example
<div ng-app="" ng-init="firstName='John';lastName='Doe'">
<p>The name is <span ng-bind="firstName + ' ' + lastName"></span></p>
</div>
Created By www.ebooktutorials.in
Example
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p>The name is {{ person.lastName }}</p>
</div>
Example
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p>The name is <span ng-bind="person.lastName"></span></p>
</div>
Example
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The third result is {{ points[2] }}</p>
</div>
Example
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The third result is <span ng-bind="points[2]"></span></p>
</div>
Created By www.ebooktutorials.in
Created By www.ebooktutorials.in
</script>
The "myApp" parameter refers to an HTML element in which the application will
run.
Now you can add controllers, directives, filters, and more, to your AngularJS
application.
Created By www.ebooktutorials.in
Add a controller to your application, and refer to the controller with the ngcontroller directive:
Example
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
AngularJS has a set of built-in directives which you can use to add functionality
to your application.
In addition you can use the module to add your own directives to your
applications:
Example
<div ng-app="myApp" w3-test-directive></div>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "I was made in a directive constructor!"
};
});
</script>
Created By www.ebooktutorials.in
Example
<!DOCTYPE html>
<html>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.
js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script src="myApp.js"></script>
<script src="myCtrl.js"></script>
</body>
</html>
myApp.js
var app = angular.module("myApp", []);
Created By www.ebooktutorials.in
myCtrl.js
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName= "Doe";
});
Example
<!DOCTYPE html>
<html>
<body>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.
js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
Created By www.ebooktutorials.in
AngularJS lets you extend HTML with new attributes called Directives.
AngularJS has a set of built-in directives which offers functionality to your
applications.
AngularJS also lets you define your own directives.
AngularJS directives are extended HTML attributes with the prefix ng-.
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.
Read about all AngularJS directives in our AngularJS directive reference.
Example
<div ng-app="" ng-init="firstName='John'">
<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>
</div>
The ng-app directive also tells AngularJS that the <div> element is the "owner"
of the AngularJS application.
Created By www.ebooktutorials.in
Example
<div ng-app="" ng-init="quantity=1;price=5">
Quantity: <input type="number" ng-model="quantity">
Costs:
<input type="number" ng-model="price">
Total in dollar: {{ quantity * price }}
</div>
Using ng-init is not very common. You will learn how to initialize
data in the chapter about controllers.
Example
<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>
Created By www.ebooktutorials.in
The ng-repeat directive actually clones HTML elements once for each item in
a collection.
The ng-repeat directive used on an array of objects:
Example
<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
Created By www.ebooktutorials.in
The ng-model directive binds the value of HTML controls (input, select,
textarea) to application data.
The ng-model directive can also:
Created By www.ebooktutorials.in
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
<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>
Element name
Attribute
Class
Comment
Created By www.ebooktutorials.in
Attribute
<div w3-test-directive></div>
Class
<div class="w3-test-directive"></div>
Comment
<!-- directive: w3-test-directive -->
You can restrict your directives to only be invoked by some of the methods.
Example
By adding a restrict property with the value "A", the directive can only be invoked
by attributes:
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
restrict : "A",
template : "<h1>Made by a directive!</h1>"
};
});
E
A
C
M
for
for
for
for
Element name
Attribute
Class
Comment
By default the value is EA, meaning that both Element names and attribute
names can invoke the directive.
Created By www.ebooktutorials.in
The ng-model directive binds the value of HTML controls (input, select,
textarea) to application data.
With the ng-model directive you can bind the value of an input field to a
variable created in AngularJS.
Example
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="name">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>
The binding goes both ways. If the user changes the value inside the input field,
the AngularJS property will also change it's value:
Example
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="name">
<h1>You entered: {{name}}</h1>
</div>
Created By www.ebooktutorials.in
The ng-model directive can provide type validation for application data
(number, e-mail, required):
Example
<form ng-app="" 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>
In the example above, the span will be displayed only if the expression in
the ng-show attribute returns true.
The ng-model directive can provide status for application data (invalid, dirty,
touched, error):
Example
<form ng-app="" name="myForm" ng-init="myText = '[email protected]'">
Email:
<input type="email" name="myAddress" ng-model="myText" required></p>
<h1>Status</h1>
{{myForm.myAddress.$valid}}
{{myForm.myAddress.$dirty}}
{{myForm.myAddress.$touched}}
</form>
Created By www.ebooktutorials.in
The ng-model directive provides CSS classes for HTML elements, depending on
their status:
Example
<style>
input.ng-invalid {
background-color: lightblue;
}
</style>
<body>
<form ng-app="" name="myForm">
Enter your name:
<input name="myAddress" ng-model="text" required>
</form>
ng-empty
ng-not-empty
ng-touched
ng-untouched
ng-valid
ng-invalid
ng-dirty
ng-pending
ng-pristine
Created By www.ebooktutorials.in
AngularJS Example
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
Application explained:
The AngularJS application is defined by ng-app="myApp". The application
runs inside the <div>.
The ng-controller="myCtrl" attribute is an AngularJS directive. It defines a
controller.
Created By www.ebooktutorials.in
AngularJS Example
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
Created By www.ebooktutorials.in
AngularJS Example
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script src="personController.js"></script>
Created By www.ebooktutorials.in
AngularJS Example
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
<script src="namesController.js"></script>
Created By www.ebooktutorials.in
The scope is the binding part between the HTML (view) and the JavaScript
(controller).
The scope is an object with the available properties and methods.
The scope is available for both the view and the controller.
When you make a controller in AngularJS, you pass the $scope object as an
argument:
Example
Properties made in the cont roller, can be referred to in the view:
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{carname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.carname = "Volvo";
});
</script>
When adding properties to the $scope object in the controller, the view (HTML)
gets access to these properties.
In the view, you do not use the prefix $scope, you just refer to a
propertyname, like{{carname}}.
Created By www.ebooktutorials.in
Example
If you make changes in the view, the model and the controller will be updated:
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="name">
<h1>My name is {{name}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Dow";
});
</script>
It is important to know which scope you are dealing with, at any time.
In the two examples above there is only one scope, so knowing your scope is
not an issue, but for larger applications there can be sections in the HTML DOM
which can only access certain scopes.
Created By www.ebooktutorials.in
Example
When dealing with the ng-repeat directive, each repetition has access to the
current repetition object:
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in names">{{x}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
});</script>
Each <li> element has access to the current repetition object, in this case a
string, which is referred to by using x.
All applications have a $rootScope which is the scope created on the HTML
element that contains the ng-app directive.
The rootScope is available in the entire application.
If a variable has the same name in both the current scope and in the rootScope,
the application use the one in the current scope.
Example
A variable named "color" exists in both the controller's scope and in the
rootScope:
<body ng-app="myApp">
<p>The rootScope's favorite color:</p>
<h1>{{color}}</h1>
<div ng-controller="myCtrl">
<p>The scope of the controller's favorite color:</p>
<h1>{{color}}</h1>
</div>
<p>The rootScope's favorite color is still:</p>
<h1>{{color}}</h1>
<script>
var app = angular.module('myApp', []);
app.run(function($rootScope) {
$rootScope.color = 'blue';
});
app.controller('myCtrl', function($scope) {
$scope.color = "red";
});</script></body>
Created By www.ebooktutorials.in
Example
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ lastName | uppercase }}</p>
</div>
Created By www.ebooktutorials.in
Example
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ lastName | lowercase }}</p>
</div>
Filters are added to directives, like ng-repeat, by using the pipe character |,
followed by a filter:
Example
The orderBy filter sorts an array:
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
Example
<div ng-app="myApp" ng-controller="costCtrl">
<h1>Price: {{ price | currency }}</h1>
</div>
Created By www.ebooktutorials.in
Example
Return the names that contains the letter "i":
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | filter : 'i'">
{{ x }}
</li>
</ul>
</div>
By setting the ng-model directive on an input field, we can use the value of the
input field as an expression in a filter.
Type a letter in the input field, and the list will shrink/grow depending on the
match:
Jani
Carl
Margareth
Hege
Joe
Gustav
Birgit
Mary
Kai
Created By www.ebooktutorials.in
Example
<div ng-app="myApp" ng-controller="namesCtrl">
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in names | filter : test">
{{ x }}
</li>
</ul>
</div>
Country
Jani
Norway
Carl
Sweden
Margareth
England
Hege
Norway
Joe
Denmark
Gustav
Sweden
Birgit
Denmark
Mary
England
Kai
Norway
Created By www.ebooktutorials.in
By adding the ng-click directive on the table headers, we can run a function
that changes the sorting order of the array:
Example
<div ng-app="myApp" ng-controller="namesCtrl">
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
$scope.orderByMe = function(x) {
$scope.myOrderBy = x;
}
});
</script>
Created By www.ebooktutorials.in
You can make your own filters by register a new filter factory function with your
module:
Example
Make a custom filter called "myFormat":
<ul ng-app="myApp" ng-controller="namesCtrl">
<li ng-repeat="x in names">
{{x | myFormat}}
</li>
</ul>
<script>
var app = angular.module('myApp', []);
app.filter('myFormat', function() {
return function(x) {
var i, c, txt = "";
x = x.split("")
for (i = 0; i < x.length; i++) {
c = x[i];
if (i % 2 == 0) {
c = c.toUpperCase();
}
txt += c;
}
return txt;
};
});
app.controller('namesCtrl', function($scope) {
$scope.names =
['Jani', 'Carl', 'Margareth', 'Hege', 'Joe', 'Gustav','Birgit', 'Mary', 'Kai'
];
});
</script>
Created By www.ebooktutorials.in
In AngularJS you can make your own service, or use one of the many builtin services.
Example
Use the $location service in a controller:
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $location) {
myUrl = $location.absUrl();
});
Note that the $location service is passed in to the controller as an argument.
In order to use the service in the controller, it must be defined as a
dependency.
For many services, like the $location service, it seems like you could use
objects that are already in the DOM, like the window.location object, and you
could, but it would have some limitations, at least for your AngularJS
application.
Created By www.ebooktutorials.in
The $http service is one of the most common used services in AngularJS
applications. The service makes a request to the server, and lets your
application handle the response.
Example
Use the $http service to request data from the server:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
This example demonstrates a very simple use of the $http service.
Example
Display a new message after two seconds:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "Hello World!";
$timeout(function () {
$scope.myHeader = "How are you today?";
}, 2000);
});
Created By www.ebooktutorials.in
Example
Display the time every second:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});
To use your custom made service, add it as a dependency when defining the
filter:
Example
Use the custom made service named hexafy to convert a number into a
hexadecimal number:
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});
Created By www.ebooktutorials.in
Once you have created a service, and connected it to your application, you can
use the service in any controller, directive, filter, or even inside other services.
To use the service inside a filter, add it as a dependency when defining the
filter:
The service hexafy used in the filter myFormat:
app.filter('myFormat',['hexify', function(hexify) {
return function(x) {
return hexify.myFunc(x);
};
}]);
You can use the filter when displaying values from an object, or an array:
Create a service named hexafy:
<ul>
<li ng-repeat="x in counts">{{x | myFormat}}</li>
</ul>
Created By www.ebooktutorials.in
The AngularJS $http service makes a request to the server, and returns a
response.
Example
Make a simple request to the server, and display the result in a header:
<div ng-app="myApp" ng-controller="myCtrl">
<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1></div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm")
.then(function(response) {
$scope.myWelcome = response.data;
});
});</script>
The example above uses the .get method of the $http service.
The .get method is a shortcut method of the $http service. There are several
shortcut methods:
.delete()
.get()
.head()
.jsonp()
.patch()
.post()
.put()
Content Downloaded from www.w3schools.com
Created By www.ebooktutorials.in
The methods above are all shortcuts of calling the $http service:
Example
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http({
method : "GET",
url : "welcome.htm"
}).then(function mySucces(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
The example above executes the $http service with one argument, an object
specifying the HTTP method, the url, what to do on success, and what to to on
failure.
Example
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm")
.then(function(response) {
$scope.content = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statustext;
});
});
Created By www.ebooktutorials.in
Example
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("wrongfilename.htm")
.then(function(response) {
//First function handles success
$scope.content = response.data;
}, function(response) {
//Second function handles error
$scope.content = "Something went wrong";
});
});
The data you get from the response is expected to be in JSON format.
JSON is a great way of transporting data, and it is easy to use within AngularJS,
or any other JavaScript.
Example: On the server we have a file that returns a JSON object containing 15
customers, all wrapped in array called records.
Example
The ng-repeat directive is perfect for looping through an array:
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("customers.php").then(function(response) {
$scope.myData = response.data.records;
});
});
</script>
Created By www.ebooktutorials.in
Application explained:
The application defines the customersCtrl controller, with
a $scope and $http object.
Created By www.ebooktutorials.in
AngularJS Example
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.then(function (response) {$scope.names = response.data.records;});
});</script>
CSS Style
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}</style>
Content Downloaded from www.w3schools.com
Created By www.ebooktutorials.in
AngularJS Example
<table>
<tr ng-repeat="x in names | orderBy : 'Country'">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
AngularJS Example
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country | uppercase }}</td>
</tr>
</table>
AngularJS Example
<table>
<tr ng-repeat="x in names">
<td>{{ $index + 1 }}</td>
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
Created By www.ebooktutorials.in
AngularJS Example
<table>
<tr ng-repeat="x in names">
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Name }}</td>
<td ng-if="$even">{{ x.Name }}</td>
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Country }}</td>
<td ng-if="$even">{{ x.Country }}</td>
</tr>
</table>
Created By www.ebooktutorials.in
Example
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names">
</select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
});
</script>
You can also use the ng-repeat directive to make the same dropdown list:
Example
<select>
<option ng-repeat="x in names">{{x}}</option>
</select>
Because 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, but the ngoptions directive was made especially for filling a dropdown list with options,
and has at least one important advantage:
Created By www.ebooktutorials.in
The ng-repeat directive has it's limitations, the selected value must be a
string:
Example
Using ng-repeat:
<select ng-model="selectedCar">
<option ng-repeat="x in cars" value="{{x.model}}">{{x.model}}</option>
</select>
<h1>You selected: {{selectedCar}}</h1>
When using the ng-options directive, the selected value can be an object:
Example
Using ng-options:
<select ng-model="selectedCar" ng-options="x.model for x in cars">
</select>
<h1>You selected: {{selectedCar.model}}</h1>
<p>It's color is: {{selectedCar.color}}</p>
When the selected value can be an object, it can hold more information, and
your application can be more flexible.
We will use the ng-options directive in this tutorial.
Created By www.ebooktutorials.in
In the previous examples the data source was an array, but we can also use an
object.
Assume you have an object with key-value pairs:
$scope.cars
car01 :
car02 :
car03 :
};
= {
"Ford",
"Fiat",
"Volvo"
Example
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>
<h1>You selected: {{selectedCarl}}</h1>
Example
The selected value will still be the value in a key-value pair, only this time it is
an object:
$scope.cars = {
car01 : {brand : "Ford", model : "Mustang", color : "red"},
car02 : {brand : "Fiat", model : "500", color : "white"},
car03 : {brand : "Volvo", model : "XC90", color : "black"}
};
The options in the dropdown list does not have be the key in a key-value pair,
it can also be the value, or a property of the value object:
Example
<select ng-model="selectedCar" ng-options="y.brand for (x, y) in cars">
</select>
Created By www.ebooktutorials.in
The code from the previous chapter can also be used to read from
databases.
AngularJS Example
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers_mysql.php")
.then(function (response) {$scope.names = response.data.records;});
});
</script>
Created By www.ebooktutorials.in
AngularJS Example
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers_sql.aspx")
.then(function (response) {$scope.names = response.data.records;});
});
</script>
The following section is a listing of the server code used to fetch SQL data.
1.
2.
3.
4.
Using
Using
Using
Using
Created By www.ebooktutorials.in
Requests for data from a different server (than the requesting page), are
called cross-site HTTP requests.
Cross-site requests are common on the web. Many pages load CSS, images,
and scripts from different servers.
In modern browsers, cross-site HTTP requests from scripts are restricted
to same site for security reasons.
The following line, in our PHP examples, has been added to allow cross-site
access.
header("Access-Control-Allow-Origin: *");
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$result = $conn->query("SELECT CompanyName, City, Country FROM Customers");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"Name":"' . $rs["CompanyName"] . '",';
$outp .= '"City":"'
. $rs["City"]
. '",';
$outp .= '"Country":"'. $rs["Country"]
. '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>
Created By www.ebooktutorials.in
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=ISO-8859-1");
$conn = new COM("ADODB.Connection");
$conn->open("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb");
$rs = $conn->execute("SELECT CompanyName, City, Country FROM Customers");
$outp = "";
while (!$rs->EOF) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"Name":"' . $rs["CompanyName"] . '",';
$outp .= '"City":"'
. $rs["City"]
. '",';
$outp .= '"Country":"'. $rs["Country"]
. '"}';
$rs->MoveNext();
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo ($outp);
?>
Created By www.ebooktutorials.in
source=Northwind.mdb")
objAdapter = New OledbDataAdapter("SELECT CompanyName, City, Country FROM
Customers", conn)
objAdapter.Fill(objDataSet, "myTable")
objTable=objDataSet.Tables("myTable")
outp = ""
c = chr(34)
for each x in objTable.Rows
if outp <> "" then outp = outp & ","
outp = outp & "{" & c & "Name"
& c & ":" & c & x("CompanyName") & c & ","
outp = outp &
c & "City"
& c & ":" & c & x("City")
& c & ","
outp = outp &
c & "Country" & c & ":" & c & x("Country")
& c & "}"
next
outp ="{" & c & "records" & c & ":[" & outp & "]}"
response.write(outp)
conn.close
%>
@{
Response.AppendHeader("Access-Control-Allow-Origin", "*")
Response.AppendHeader("Content-type", "application/json")
var db = Database.Open("Northwind");
var query = db.Query("SELECT CompanyName, City, Country FROM Customers");
var outp =""
var c = chr(34)
}
@foreach(var row in query)
{
if outp <> "" then outp = outp + ","
outp = outp + "{" + c + "Name"
+ c + ":" + c + @row.CompanyName + c + ","
outp = outp +
c + "City"
+ c + ":" + c + @row.City
+ c + ","
outp = outp +
c + "Country" + c + ":" + c + @row.Country
+ c + "}"
}
outp ="{" + c + "records" + c + ":[" + outp + "]}"
@outp
Created By www.ebooktutorials.in
AngularJS Example
<div ng-app="" ng-init="mySwitch=true">
<p>
<button ng-disabled="mySwitch">Click Me!</button>
</p>
<p>
<input type="checkbox" ng-model="mySwitch">Button
</p>
<p>
{{ mySwitch }}
</p>
</div>
Application explained:
The ng-disabled directive binds the application data mySwitch to the HTML
button's disabledattribute.
The ng-model directive binds the value of the HTML checkbox element to the
value ofmySwitch.
If the value of mySwitch evaluates to true, the button will be disabled:
Created By www.ebooktutorials.in
<p>
<button disabled>Click Me!</button>
</p>
If the value of mySwitch evaluates to false, the button will not be disabled:
<p>
<button>Click Me!</button>
</p>
AngularJS Example
<div ng-app="">
<p ng-show="true">I am visible.</p>
<p ng-show="false">I am not visible.</p>
</div>
The ng-show directive shows (or hides) an HTML element based on the value of
ng-show.
You can use any expression that evaluates to true or false:
AngularJS Example
<div ng-app="" ng-init="hour=13">
<p ng-show="hour > 12">I am visible.</p>
</div>
In the next chapter, there are more examples, using the click of a
button to hide HTML elements.
Created By www.ebooktutorials.in
AngularJS Example
<div ng-app="">
<p ng-hide="true">I am not visible.</p>
<p ng-hide="false">I am visible.</p>
</div>
Created By www.ebooktutorials.in
You can add AngularJS event listeners to your HTML elements by using one or
more of these directives:
ng-blur
ng-change
ng-click
ng-copy
ng-cut
ng-dblclick
ng-focus
ng-keydown
ng-keypress
ng-keyup
ng-mousedown
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
ng-mouseup
ng-paste
The event directives allows us to run AngularJS functions at certain user events.
An AngularJS event will not overwrite an HTML event, both events will be
executed.
Created By www.ebooktutorials.in
Mouse events occur when the cursor moves over an element, in this order:
1.
2.
3.
4.
ng-mouseenter
ng-mouseover
ng-mousemove
ng-mouseleave
Example
Increase the count variable when the mouse moves over the DIV element:
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-mousemove="count = count + 1">Mouse over me!</button>
<h1>{{ count }}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
Created By www.ebooktutorials.in
The ng-click directive defines AngularJS code that will be executed when the
element is being clicked.
Example
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="count = count + 1">Click me!</button>
<p>{{ count }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
Example
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="myFunction()">Click me!</button>
<p>{{ count }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
$scope.myFunction = function() {
$scope.count++;
}
});
</script>
Created By www.ebooktutorials.in
If you want to show a section of HTML code when a button is clicked, and hide
when the button is clicked again, like a dropdown menu, make the button
behave like a toggle switch:
Click Me
Example
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="myFunc()">Click Me!</button>
<div ng-show="showMe">
<h1>Menu:</h1>
<div>Pizza</div>
<div>Pasta</div>
<div>Pesce</div>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.showMe = false;
$scope.myFunc = function() {
$scope.showMe = !$scope.showMe;
}
});
</script>
You can pass the $event object as an argument when calling the function.
The $event object contains the browser's event object:
Created By www.ebooktutorials.in
Example
<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-mousemove="myFunc($event)">Mouse Over Me!</h1>
<p>Coordinates: {{x + ', ' + y}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.myFunc = function(myE) {
$scope.x = myE.clientX;
$scope.y = myE.clientY;
}
});
</script>
Created By www.ebooktutorials.in
input elements
select elements
button elements
textarea elements
Example
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.firstname = "John";
});
</script>
Created By www.ebooktutorials.in
Example
<form>
First Name: <input type="text" ng-model="firstname">
</form>
<h1>You entered: {{firstname}}</h1>
A checkbox has the value true or false. Apply the ng-model directive to a
checkbox, and use it's value in your application.
Example
Show the header if the checkbox is checked:
<form>
Check to show a header:
<input type="checkbox" ng-model="myVar">
</form>
<h1 ng-show="myVar">My Header</h1>
Example
Display some text, based on the value of the selected radio button:
<form>
Pick a topic:
<input type="radio" ng-model="myVar" value="dogs">Dogs
<input type="radio" ng-model="myVar" value="tuts">Tutorials
<input type="radio" ng-model="myVar" value="cars">Cars
</form>
Content Downloaded from www.w3schools.com
Created By www.ebooktutorials.in
Example
Display some text, based on the value of the selected option:
<form>
Select a topic:
<select ng-model="myVar">
<option value="">
<option value="dogs">Dogs
<option value="tuts">Tutorials
<option value="cars">Cars
</select>
</form>
The value of myVar will be either dogs, tuts, or cars.
First Name:
Last Name:
RESET
form = {"firstName":"John","lastName":"Doe"}
master = {"firstName":"John","lastName":"Doe"}
Created By www.ebooktutorials.in
Application Code
<div ng-app="myApp" ng-controller="formCtrl">
<form novalidate>
First Name:<br>
<input type="text" ng-model="user.firstName"><br>
Last Name:<br>
<input type="text" ng-model="user.lastName">
<br><br>
<button ng-click="reset()">RESET</button>
</form>
<p>form = {{user}}</p>
<p>master = {{master}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.master = {firstName: "John", lastName: "Doe"};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
});
</script>
Created By www.ebooktutorials.in
Use the HTML5 attribute required to specify that the input field must be filled
out:
Example
The input field is required:
<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>
<p>The input's valid state is:</p>
<h1>{{myForm.myInput.$valid}}</h1>
Created By www.ebooktutorials.in
Use the HTML5 type email to specify that the value must be an e-mail:
Example
The input field has to be an e-mail:
<form name="myForm">
<input name="myInput" ng-model="myInput" type="email">
</form>
<p>The input's valid state is:</p>
<h1>{{myForm.myInput.$valid}}</h1>
AngularJS is constantly updating the state of both the form and the input fields.
Input fields have the following states:
They are all properties of the input field, and are either true or false.
Forms have the following states:
They are all properties of the form, and are either true or false.
Created By www.ebooktutorials.in
You can use these states to show meaningful messages to the user. Example, if
a field is required, and the user leaves it blank, you should give the user a
warning:
Example
Show an error message if the field has been touched AND is empty:
<input name="myName" ng-model="myName" required>
<span ng-show="myForm.myName.$touched && myForm.myName.$invalid">The name is
required.</span>
AngularJS adds CSS classes to forms and input fields depending on their states.
The following classes are added to, or removed from, input fields:
Created By www.ebooktutorials.in
Example
Apply styles, using standard CSS:
<style>
input.ng-invalid {
background-color: pink;
}
input.ng-valid {
background-color: lightgreen;
}
</style>
Forms can also be styled:
Example
Apply styles for unmodified (pristine) forms, and for modified forms:
<style>
form.ng-pristine {
background-color: lightblue;
}
form.ng-dirty {
background-color: pink;
}
</style>
To create your own validation function is a bit more tricky. You have to add a
new directive to your application, and deal with the validation inside a function
with certain specified arguments.
Created By www.ebooktutorials.in
Example
Create your own directive, containing a custom validation function, and refer to
it by using my-directive.
The field will only be valid if the value contains the character "e":
<form name="myForm">
<input name="myInput" ng-model="myInput" required my-directive>
</form>
<script>
var app = angular.module('myApp', []);
app.directive('myDirective', function() {
return {
require: 'ngModel',
link: function(scope, element, attr, mCtrl) {
function myValidation(value) {
if (value.indexOf("e") > -1) {
mCtrl.$setValidity('charE', true);
} else {
mCtrl.$setValidity('charE', false);
}
return value;
}
mCtrl.$parsers.push(myValidation);
}
};
});
</script>
In HTML, the new directive will be referred to by using the attribute mydirective.
In the JavaScript we start by adding a new directive named myDirective.
Remember, when naming a directive, you must use a camel case
name, myDirective, but when invoking it, you must use - separated
name, my-directive.
Then, return an object where you specify that we require ngModel, which is the
ngModelController.
Created By www.ebooktutorials.in
Make a linking function which takes some arguments, where the fourth
argument, mCtrl, is the ngModelController,
Then specify a function, in this case named myValidation, which takes one
argument, this argument is the value of the input element.
Test if the value contains the letter "e", and set the validity of the model
controller to either true or false.
At last, mCtrl.$parsers.push(myValidation); will add
the myValidation function to an array of other functions, which will be
executed every time the input value changes.
Validation Example
<!DOCTYPE html>
<html>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.
js"></script>
<body>
<h2>Validation Example</h2>
<form ng-app="myApp" ng-controller="validateCtrl"
name="myForm" novalidate>
<p>Username:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="myForm.user.$dirty &&
myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">Username is required.</span>
</span>
</p>
<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty &&
myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>
<p>
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
Content Downloaded from www.w3schools.com
Created By www.ebooktutorials.in
</p>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.user = 'John Doe';
$scope.email = '[email protected]';
});
</script>
</body>
</html>
The AngularJS directive ng-model binds the input elements to the model.
The model object has two properties: user and email.
Because of ng-show, the spans with color:red are displayed only when user or
email is $dirtyand $invalid.
Created By www.ebooktutorials.in
The AngularJS Global API is a set of global JavaScript functions for performing
common tasks like:
Comparing objects
Iterating objects
Converting data
The Global API functions are accessed using the angular object.
Below is a list of some common API functions:
API
Description
angular.lowercase()
angular.uppercase()
angular.isString()
angular.isNumber()
Created By www.ebooktutorials.in
Example
<div ng-app="myApp" ng-controller="myCtrl">
<p>{{ x1 }}</p>
<p>{{ x2 }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.x1 = "JOHN";
$scope.x2 = angular.lowercase($scope.x1);
});
</script>
Example
<div ng-app="myApp" ng-controller="myCtrl">
<p>{{ x1 }}</p>
<p>{{ x2 }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.x1 = "John";
$scope.x2 = angular.uppercase($scope.x1);
});
</script>
Example
<div ng-app="myApp" ng-controller="myCtrl">
<p>{{ x1 }}</p>
<p>{{ x2 }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.x1 = "JOHN";
$scope.x2 = angular.isString($scope.x1);
});</script>
Content Downloaded from www.w3schools.com
Created By www.ebooktutorials.in
Example
<div ng-app="myApp" ng-controller="myCtrl">
<p>{{ x1 }}</p>
<p>{{ x2 }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.x1 = "JOHN";
$scope.x2 = angular.isNumber($scope.x1);
});
</script>
Created By www.ebooktutorials.in
You can easily use w3.css style sheet together with AngularJS. This chapter
demonstrates how.
To include W3.CSS in your AngularJS application, add the following line to the
head of your document:
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
HTML Code
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.
js"></script>
<body ng-app="myApp" ng-controller="userCtrl">
<div class="w3-container">
<h3>Users</h3>
<table class="w3-table w3-bordered w3-striped">
<tr>
<th>Edit</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
Created By www.ebooktutorials.in
Created By www.ebooktutorials.in
AngularJS
Directive
Description
<body ng-app
<body ngcontroller
<tr ng-repeat
<button ng-click
<h3 ng-show
<h3 ng-hide
<input ng-model
<button ngdisabled
Created By www.ebooktutorials.in
Element
Class
Defines
<div>
w3-container
A content container
<table>
w3-table
A table
<table>
w3-bordered
A bordered table
<table>
w3-striped
A striped table
<button>
w3-btn
A button
<button>
w3-green
A green button
<button>
w3-ripple
<input>
w3-input
An input field
<input>
w3-border
Created By www.ebooktutorials.in
myUsers.js
angular.module('myApp', []).controller('userCtrl', function($scope) {
$scope.fName = '';
$scope.lName = '';
$scope.passw1 = '';
$scope.passw2 = '';
$scope.users = [
{id:1, fName:'Hege', lName:"Pege" },
{id:2, fName:'Kim', lName:"Pim" },
{id:3, fName:'Sal', lName:"Smith" },
{id:4, fName:'Jack', lName:"Jones" },
{id:5, fName:'John', lName:"Doe" },
{id:6, fName:'Peter',lName:"Pan" }
];
$scope.edit = true;
$scope.error = false;
$scope.incomplete = false;
$scope.hideform = true;
$scope.editUser = function(id) {
$scope.hideform = false;
if (id == 'new') {
$scope.edit = true;
$scope.incomplete = true;
$scope.fName = '';
$scope.lName = '';
} else {
$scope.edit = false;
$scope.fName = $scope.users[id-1].fName;
$scope.lName = $scope.users[id-1].lName;
}
};
$scope.$watch('passw1',function()
$scope.$watch('passw2',function()
$scope.$watch('fName', function()
$scope.$watch('lName', function()
{$scope.test();});
{$scope.test();});
{$scope.test();});
{$scope.test();});
$scope.test = function() {
if ($scope.passw1 !== $scope.passw2) {
Created By www.ebooktutorials.in
$scope.error = true;
} else {
$scope.error = false;
}
$scope.incomplete = false;
if ($scope.edit && (!$scope.fName.length ||
!$scope.lName.length ||
!$scope.passw1.length || !$scope.passw2.length)) {
$scope.incomplete = true;
}
};
});
Scope Properties
Used for
$scope.fName
$scope.lName
$scope.passw1
$scope.passw2
$scope.users
$scope.edit
$scope.hideform
$scope.error
Created By www.ebooktutorials.in
$scope.incomplete
$scope.editUser
$scope.$watch
$scope.test
Created By www.ebooktutorials.in
With AngularJS, you can include HTML content using the ng-include directive:
Example
<body ng-app="">
<div ng-include="'myFile.htm'"></div>
</body>
The HTML files you include with the ng-include directive, can also contain
AngularJS code:
myTable.htm:
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
Include the file "myTable.htm" in your web page, and all AngularJS code will be
executed, even the code inside the included file:
Created By www.ebooktutorials.in
Example
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<div ng-include="'myTable.htm'"></div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("customers.php").then(function (response) {
$scope.names = response.data.records;
});
});
</script>
By default, the ng-include directive does not allow you to include files from
other domains.
To include files from another domain, you can add a whitelist of legal files
and/or domains in the config function of your application:
Example:
<body ng-app="myApp">
<div ng-include="'http://www.refsnesdata.no/angular_include.asp'"></div>
<script>
var app = angular.module('myApp', [])
app.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'http://www.refsnesdata.no/**'
]);
});
</script>
</body>
Be sure that the server on the destination allows cross domain file
access.
Created By www.ebooktutorials.in
Example:
Check the checkbox to hide the DIV:
<body ng-app="ngAnimate">
Hide the DIV: <input type="checkbox" ng-model="myCheck">
<div ng-hide="myCheck"></div>
</body>
To make your applications ready for animations, you must include the AngularJS
Animate library:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angularanimate.js"></script>
Created By www.ebooktutorials.in
<body ng-app="ngAnimate">
Example
<body ng-app="myApp">
<h1>Hide the DIV: <input type="checkbox" ng-model="myCheck"></h1>
<div ng-hide="myCheck"></div>
<script>
var app = angular.module('myApp', ['ngAnimate']);
</script>
ng-show
ng-hide
ng-class
ng-view
ng-include
ng-repeat
ng-if
ng-switch
The ng-show and ng-hide directives adds or removes a ng-hide class value.
The other directives adds a ng-enter class value when they enter the DOM,
and a ng-leave attribute when they are removed from the DOM.
The ng-repeat directive also adds a ng-move class value when the HTML
element changes position.
Created By www.ebooktutorials.in
In addition, during the animation, the HTML element will have a set of class
values, which will be removed when the animation has finished. Example:
the ng-hide directive will add these class values:
ng-animate
ng-hide-animate
ng-hide-add (if the element will be hidden)
ng-hide-remove (if the element will be showed)
ng-hide-add-active (if the element will be hidden)
ng-hide-remove-active (if the element will be showed)
We can use CSS transitions or CSS animations to animate HTML elements. This
tutorial will show you both.
To learn more about CSS Animation, study CSS Transition Tutorial and CSS
Animation Tutorial.
CSS transitions allows you to change CSS property values smoothly, from one
value to another, over a given duration:
Example:
When the DIV element gets the .ng-hide class, the transition will take 0.5
seconds, and the height will smoothly change from 100px to 0:
<style>
div {
transition: all linear 0.5s;
background-color: lightblue;
height: 100px;
}
.ng-hide {
height: 0;
}
</style>
Created By www.ebooktutorials.in
CSS Animations allows you to change CSS property values smoothly, from one
value to another, over a given duration:
Example
When the DIV element gets the .ng-hide class, the myChange animation will
run, which will smoothly change the height from 100px to 0:
<style>
@keyframes myChange {
from {
height: 100px;
} to {
height: 0;
}
}
div {
height: 100px;
background-color: lightblue;
}
div.ng-hide {
animation: 0.5s myChange;
}
</style>
Created By www.ebooktutorials.in
You have learned more than enough to create your first AngularJS application:
My Note
Save Clear
Number of characters left: 100
AngularJS Example
<html ng-app="myNoteApp">
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.
js"></script>
<body>
<div ng-controller="myNoteCtrl">
<h2>My Note</h2>
<p><textarea ng-model="message" cols="40" rows="10"></textarea></p>
Created By www.ebooktutorials.in
<p>
<button ng-click="save()">Save</button>
<button ng-click="clear()">Clear</button>
</p>
<p>Number of characters left: <span ng-bind="left()"></span></p>
</div>
<script src="myNoteApp.js"></script>
<script src="myNoteCtrl.js"></script>
</body>
</html>
Created By www.ebooktutorials.in
The two ng-click events invoke the controller functions clear() and save():
<button ng-click="save()">Save</button>
<button ng-click="clear()">Clear</button>
Your application libraries are added to the page (after the library):
<script src="myNoteApp.js"></script>
<script src="myNoteCtrl.js"></script>
Above you have the skeleton (scaffolding) of a real life AngularJS, single page
application (SPA).
The <html> element is the "container" for the AngularJS application (ngapp=).
A <div> elements defines the scope of an AngularJS controller (ngcontroller=).
You can have many controllers in one application.
An application file (my...App.js) defines the application module code.
One or more controller files (my...Ctrl.js) defines the controller code.
Created By www.ebooktutorials.in
Created By www.ebooktutorials.in
ng-app
Defines the root element of an application.
Example
Let the body element become the root element for the AngularJS application:
<body ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</body>
The ng-app directive tells AngularJS that this is the root element of the
AngularJS application.
All AngularJS applications must have a root element.
You can only have one ng-app directive in your HTML document. If more than
one ng-appdirective appears, the first appearance will be used.
<element ng-app="modulename">
...
content inside the ng-app root element can contain AngularJS code
...
</element>
Created By www.ebooktutorials.in
Value
Description
modulename
Example
Load a module to run in the application
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
ng-bind
Example
Bind the innerHTML of the <p> element to the variable myText:
<div ng-app="" ng-init="myText='Hello World!'">
<p ng-bind="myText"></p>
</div>
Created By www.ebooktutorials.in
<element ng-bind="expression"></element>
Or as a CSS class:
<element class="ng-bind: expression"></element>
Value
Description
expression
ng-bind-html
Example
Bind the innerHTML of the <p> element to the variable myText:
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.
js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angularsanitize.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p ng-bind-html="myText"></p>
</div>
<script>
var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
$scope.myText = "My name is: <h1>John Doe</h1>";
});
</script>
Created By www.ebooktutorials.in
<element ng-bind-html="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-bind-template
Example
Bind two expressions to the <p> element:
<div ng-app="myApp" ng-bind-template="{{firstName}} {{lastName}}" ngcontroller="myCtrl"></div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
<element ng-bind-template="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-blur
Example
Execute an expresson when the input field loses focus (onblur):
<input ng-blur="count = count + 1" ng-init="count=0" />
<h1>{{count}}</h1>
The ng-blur directive tells AngularJS what to do when an HTML element loses
focus.
The ng-blur directive from AngularJS will not override the element's original
onblur event, both the ng-blur expression and the original onblur event will be
executed.
<element ng-blur="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-change
Example
Execute a function when the value of the input field changes:
<body ng-app="myApp">
<div ng-controller="myCtrl">
<input type="text" ng-change="myFunc()" ng-model="myValue" />
<p>The input field has changed {{count}} times.</p>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.count = 0;
$scope.myFunc = function() {
$scope.count++;
};
}]);
</script>
</body>
The ng-change directive tells AngularJS what to do when the value of an HTML
element changes.
The ng-change directive requires a ng-model directive to be present.
The ng-change directive from AngularJS will not override the element's original
onchange event, both the ng-change expression and the original onchange
event will be executed.
The ng-change event is triggered at every change in the value. It will not wait
until all changes are made, or when the input field loses focus.
The ng-change event is only triggered if there is a actual change in the input
value, and not if the change was made from a JavaScript.
Created By www.ebooktutorials.in
<element ng-change="expression"></element>
Value
Description
expression
ng-checked
Example
Check one to check them all:
<body ng-app="">
<p>My cars:</p>
<input type="checkbox" ng-model="all"> Check all<br><br>
<input type="checkbox" ng-checked="all">Volvo<br>
<input type="checkbox" ng-checked="all">Ford<br>
<input type="checkbox" ng-checked="all">Mercedes
</body>
Created By www.ebooktutorials.in
Value
Description
expression
An expression that will set the element's checked attribute if it returns true.
ng-class
Example
Change class of a <div> element:
<select ng-model="home">
<option value="sky">Sky</option>
<option value="tomato">Tomato</option>
</select>
<div ng-class="home">
<h1>Welcome Home!</h1>
<p>I like it!</p>
</div>
The ng-class directive dynamically binds one or more CSS classes to an HTML
element.
The value of the ng-class directive can be a string, an object, or an array.
If it is a string, it should contain one or more, space-separated class names.
Created By www.ebooktutorials.in
<element ng-class="expression"></element>
Value
Description
expression
ng-class-even
Example
Set class="striped" for every other (even) table row:
<table ng-controller="myCtrl">
<tr ng-repeat="x in records" ng-class-even="'striped'">
<td>{{x.Name}}</td>
<td>{{x.Country}}</td>
</tr>
</table>
Created By www.ebooktutorials.in
<element ng-class-even="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-class-odd
Example
Set class="striped" for every other (odd) table row:
<table ng-controller="myCtrl">
<tr ng-repeat="x in records" ng-class-odd="'striped'">
<td>{{x.Name}}</td>
<td>{{x.Country}}</td>
</tr>
</table>
<element ng-class-odd="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-click
Example
Increase the count variable by one, each time the button is clicked:
<button ng-click="count = count + 1" ng-init="count=0">OK</button>
<element ng-click="expression"></element>
Value
Description
expression
Example
Execute a function, in AngularJS, when a button is clicked:
<body ng-app="myApp">
<div ng-controller="myCtrl">
<button ng-click="myFunc()">OK</button>
<p>The button has been clicked {{count}} times.</p>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.count = 0;
$scope.myFunc = function() {
$scope.count++;
};
}]);</script></body>
Created By www.ebooktutorials.in
ng-cloak
Example
Prevent the application from flicker at page load:
<div ng-app="">
<p ng-cloak>{{ 5 + 5 }}</p>
</div>
<element ng-cloak></element>
Created By www.ebooktutorials.in
ng-controller
Example
Add a controller to handle your application variables:
<div ng-app="myApp" ng-controller="myCtrl">
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
<element ng-controller="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-copy
Example
Execute an expresson when the text of the input field is being copied:
<input ng-copy="count = count + 1" ng-init="count=0" value="Copy this text"/>
<element ng-copy="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-csp
Example
Change the way AngularJS behaves regarding "eval" and inline styles:
<body ng-app="" ng-csp>
...
Value
Description
no-unsafe-eval
no-inline-style
The value can be empty, meaning neither eval or inline styles are allowed.
The value can be one of the two values described.
The value can be both values, separated by a semicolon, but that will have
the same meaning as an empty value.
Created By www.ebooktutorials.in
ng-cut
Example
Execute an expresson when the text of the input field is being cut:
<input ng-cut="count = count + 1" ng-init="count=0" value="Cut this text" />
The ng-cut directive tells AngularJS what to do when you cut the text of an
HTML element.
The ng-cut directive from AngularJS will not override the element's original
oncut event, both the ng-cut expression and the original oncut event will be
executed.
<element ng-cut="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-dblclick
Example
Increase the count variable by one, each time the header is double-clicked:
<h1 ng-dblclick="count = count + 1" ng-init="count=0">Welcome</h1>
<element ng-dblclick="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-disabled
Example
Disable / enable the input field:
Disable form fields: <input type="checkbox" ng-model="all">
<br>
<input type="text" ng-disabled="all">
<input type="radio" ng-disabled="all">
<select ng-disabled="all">
<option>Female</option>
<option>Male</option>
</select>
The ng-disabled directive sets the disabled attribute of a form field (input,
select, or textarea).
The form field will be disabled if the expression inside the ng-disabled
attribute returns true.
<input ng-disabled="expression"></input>
Value
Description
expression
An expression that will set the element's disabled attribute if it returns true.
Created By www.ebooktutorials.in
ng-focus
Example
Execute an expression when the input field gets focus:
<input ng-focus="count = count + 1" ng-init="count=0" />
<h1>{{count}}</h1>
The ng-focus directive tells AngularJS what to do when an HTML element gets
focus.
The ng-focus directive from AngularJS will not override the element's original
onfocus event, both will be executed.
<element ng-focus="expression"></element>
Value
Description
expression
ng-form
Specifies an HTML form to inherit controls from.
Created By www.ebooktutorials.in
ng-hide
Example
Hide a section when a checkbox is checked:
Hide HTML: <input type="checkbox" ng-model="myVar">
<div ng-hide="myVar">
<h1>Welcome</h1>
<p>Welcome to my home.</p>
</div>
The ng-hide directive hides the HTML element if the expression evaluates to
true.
<element ng-hide="expression"></element>
Value
Description
expression
An expression that will hide the element if the expression returns true.
Created By www.ebooktutorials.in
ng-href
Example
Make a href using AngularJS:
<div ng-init="myVar = 'http://www.w3schools.com'">
<h1>Tutorials</h1>
<p>Go to <a ng-href="{{myVar}}">{{myVar}}</a> to learn!</p>
</div>
The ng-href directive overrides the original href attribute of an <a> element.
The ng-href directive should be used instead of href if you have AngularJS
code inside the href value.
The ng-href directive makes sure the link is not broken even if the user clicks
the link before AngularJS has evaluated the code.
<a ng-href="string"></a>
Value
Description
string
Created By www.ebooktutorials.in
ng-if
Example
Uncheck a checkbox to remove a section:
Keep HTML: <input type="checkbox" ng-model="myVar" ng-init="myVar = true">
<div ng-if="myVar">
<h1>Welcome</h1>
<p>Welcome to my home.</p>
<hr>
</div>
The ng-if directive removes the HTML element if the expression evaluates to
false.
If the if statement evaluates to true, a copy of the Element is added in the
DOM.
The ng-if directive is different from the ng-hide which hides the display of the
element, were the ng-if directive completely removes the element from the
DOM.
<element ng-if="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-include
Example
Include HTML from an external file:
<div ng-include="'myFile.htm'"></div>
Value
Description
filename
onload
autoscroll
Optional. Whether or not the included section should be able to scroll into a
specific view.
Created By www.ebooktutorials.in
ng-init
Example
Create a variable when initiating the application:
<div ng-app="" ng-init="myText='Hello World!'">
<h1>{{myText}}</h1>
Value
Description
expression
An expression to evaluate.
ng-jq
Specifies that the application must use a library, like jQuery.
Created By www.ebooktutorials.in
ng-keydown
Example
Execute an expression at every keystroke:
<input ng-keydown="count = count + 1" ng-init="count=0" />
<h1>{{count}}</h1>
The ng-keydown directive tells AngularJS what to do when the keyboard is used
on the specific HTML element.
The ng-keydown directive from AngularJS will not override the element's
original onkeydown event, both will be executed.
The order of a key stroke is:
1. Keydown
2. Keypress
3. Keyup
<element ng-keydown="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-keypress
Example
Execute an expression at every keystroke:
<input ng-keypress="count = count + 1" ng-init="count=0" />
<h1>{{count}}</h1>
<element ng-keypress="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-keyup
Example
Execute an expression at every keystroke:
<input ng-keyup="count = count + 1" ng-init="count=0" />
<h1>{{count}}</h1>
The ng-keyup directive tells AngularJS what to do when the keyboard is used
on the specific HTML element.
The ng-keyup directive from AngularJS will not override the element's original
onkeyup event, both will be executed.
The order of a key stroke is:
1. Keydown
2. Keypress
3. Keyup
<element ng-keyup="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-list
Example
Convert user input into an array:
<div ng-app="">
<input ng-model="customers" ng-list/>
<pre>{{customers}}</pre>
The ng-list directive converts a string into an array of strings, using a comma
as the default separator.
The ng-list directive also converts the other way around, if you have a array
of strings you wish to display in an input field as a string, then put the nglist directive on the input field.
The value of the ng-list attribute defines the separator.
<element ng-list="separator"></element>
Value
Description
separator
Created By www.ebooktutorials.in
ng-model
Example
Bind the value of an input field to a variable in the scope:
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="name">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>
The ng-model directive binds an HTML form element to a variable in the scope.
If the variable does not exist in the scope, it will be created.
<element ng-model="name"></element>
Value
Description
name
The name of the property you want to bind to the form field.
Created By www.ebooktutorials.in
ng-model-options
Example
Wait with the data-binding until the field loses focus:
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="name" ng-model-options="{updateOn: 'blur'}">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>
<element ng-model-options="option"></element>
Value
Description
option
An object specifying what options the data-binding must follow. Legal objects
are:
{updateOn: 'event'} specifies that the binding should happen when the
specific event occur.
Created By www.ebooktutorials.in
{debounce : 1000} specifies how many milliseconds to wait with the binding.
{allowInvalid : true|false} specify if the binding can happen if the value di not
validate.
{getterSetter : true|false} specifies if functions bound to the model should be
treated as getters/setters.
{timezone : '0100'} Specifies what timezone should be used when working
with the Date object.
ng-mousedown
Example
Execute an expression when a mouse click occurs:
<div ng-mousedown="count = count + 1" ng-init="count=0">Click me!</div>
<h1>{{count}}</h1>
Created By www.ebooktutorials.in
<element ng-mousedown="expression"></element>
Parameter Values
Value
Description
expression
ng-mouseenter
Example
Execute an expression when the mouse cursor enters a <div> element:
<div ng-mouseenter="count = count + 1" ng-init="count=0">Mouse over me!</div>
<h1>{{count}}</h1>
<element ng-mouseenter="expression"></element>
Created By www.ebooktutorials.in
Value
Description
expression
ng-mouseleave
Example
Execute an expression when the mouse cursor leaves a <div> element:
<div ng-mouseleave="count = count + 1" ng-init="count=0">Mouse over me! (and
mouse away from me...)</div>
<h1>{{count}}</h1>
The
<element ng-mouseleave="expression"></element>
Created By www.ebooktutorials.in
Value
Description
expression
ng-mousemove
Example
Execute an expression when the mouse cursor moves over a <div> element:
<div ng-mousemove="count = count + 1" ng-init="count=0">Mouse over me!</div>
<h1>{{count}}</h1>
The
<element ng-mousemove="expression"></element>
Parameter Values
Value
expression
Description
An expression to execute when the mouse cursor moves over an element.
Created By www.ebooktutorials.in
ng-mouseover
Example
Execute an expression when the mouse cursor moves over a <div> element:
<div ng-mouseover="count = count + 1" ng-init="count=0">Mouse over me!</div>
<h1>{{count}}</h1>
The
<element ng-mouseover="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-mouseup
Example
Execute an expression when a mouse click is finished:
<div ng-mouseup="count = count + 1" ng-init="count=0">Click me!</div>
<h1>{{count}}</h1>
The
finished.
The
<element ng-mouseup="expression"></element>
Value
Description
expression
Created By www.ebooktutorials.in
ng-non-bindable
Example
This paragraph should not be compiled by AngularJS:
<div ng-app="">
<p ng-non-bindable>This code is not compiled by AngularJS: {{ 5+5 }}</p>
...
</div>
The
<element ng-non-bindable></element>
Created By www.ebooktutorials.in
ng-open
Example
Show / Hide a <details> list by clicking a checkbox:
<input type="checkbox" ng-model="showDetails">
<details ng-open="showDetails">
<summary>Copyright 1999-2016.</summary>
<p> - by Refsnes Data. All Rights Reserved.</p>
</details>
The
The details list will be visible if the expression inside the ng-open attribute
returns true.
<details ng-open="expression">...</details>
Value
Description
expression
An expression that will set the element's open attribute if it returns true.
Created By www.ebooktutorials.in
ng-options
Example
Fill options in a dropdown list by using the items of an array:
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="item for item in names"></select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
});
</script>
Value
Description
array expression
An expression that selects the specified parts of an array to fill the select
element.
Legal expressions:
Created By www.ebooktutorials.in
ng-paste
Example
Execute an expression when text is pasted into the the input:
<input ng-paste="count = count + 1" ng-init="count=0" value="Cut this text"/>
The
HTML element.
The
ng-paste directive from AngularJS will not override the element's original
<element ng-paste="expression"></element>
Created By www.ebooktutorials.in
Value
Description
expression
ng-pluralize
Specifies a message to display according to en-us localization rules.
ng-readonly
Example
Make the input field readonly:
Readonly: <input type="checkbox" ng-model="all">
<br>
<input type="text" ng-readonly="all">
The
or textarea).
The form field will be readonly if the expression inside the
readonly attribute returns true.
ng-
<input ng-readonly="expression"></input>
Created By www.ebooktutorials.in
Value
Description
expression
An expression that will set the element's readonly attribute if it returns true.
ng-repeat
Example
Write one header for each item in the records array:
<body ng-app="myApp" ng-controller="myCtrl">
<h1 ng-repeat="x in records">{{x}}</h1>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [
"Alfreds Futterkiste",
"Berglunds snabbkp",
"Centro comercial Moctezuma",
"Ernst Handel",
]
});
</script>
</body>
The
making a HTML table, displaying one table row for each object, and one table
data for each object property. See example below.
Created By www.ebooktutorials.in
<element ng-repeat="expression"></element>
Value
Description
expression
x in records
(key, value) in myObj
x in records track by $id(x)
Example
Write one table row for each item in the records array:
<table ng-controller="myCtrl" border="1">
<tr ng-repeat="x in records">
<td>{{x.Name}}</td>
<td>{{x.Country}}</td>
</tr>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [
{
"Name" : "Alfreds Futterkiste",
"Country" : "Germany"
},{
"Name" : "Berglunds snabbkp",
Created By www.ebooktutorials.in
"Country" : "Sweden"
},{
"Name" : "Centro comercial Moctezuma",
"Country" : "Mexico"
},{
"Name" : "Ernst Handel",
"Country" : "Austria"
}
]
});</script>
Example
Write one table row for each property in an object:
<table ng-controller="myCtrl" border="1">
<tr ng-repeat="(x, y) in myObj">
<td>{{x}}</td>
<td>{{y}}</td>
</tr>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.myObj = {
"Name" : "Alfreds Futterkiste",
"Country" : "Germany",
"City" : "Berlin"
}
});
</script>
Created By www.ebooktutorials.in
ng-selected
Example
Make the input field readonly:
Click here to select BMW as your favorite car:
<input type="checkbox" ng-model="mySel">
<p>My Favourite car:</p>
<select>
<option>Volvo</option>
<option ng-selected="mySel">BMW</option>
<option>Ford</option>
</select>
The
ng-selected attribute
returns true.
<option ng-selected="expression"></option>
Value
Description
expression
An expression that will set the element's selected attribute if it returns true.
Created By www.ebooktutorials.in
ng-show
Example
Show a section when a checkbox is checked:
Show HTML: <input type="checkbox" ng-model="myVar">
<div ng-show="myVar">
<h1>Welcome</h1>
<p>Welcome to my home.</p>
</div>
The
<element ng-show="expression"></element>
Value
Description
expression
An expression that will show the element only if the expression returns true.
Created By www.ebooktutorials.in
ng-src
Example
Add an image, where the src is evaluated by AngularJS:
<div ng-init="myVar = 'pic_angular.jpg'">
<h1>Angular</h1>
<img ng-src="{{myVar}}">
</div>
The
The
ng-src directive makes sure the image is not displayed wrong before
<img ng-src="string"></img>
Value
Description
string
Created By www.ebooktutorials.in
ng-srcset
Example
Add an image, where the srcset is evaluated by AngularJS:
<div ng-init="myVar = 'pic_angular.jpg'">
<h1>Angular</h1>
<img ng-srcset="{{myVar}}">
</div>
The
The
ng-srcset directive makes sure the image is not displayed wrong before
<img ng-srcset="string"></img>
Value
Description
string
Created By www.ebooktutorials.in
ng-style
Example
Add som style with AngularJS, using an object with CSS keys and values:
<body ng-app="myApp" ng-controller="myCtrl">
<h1 ng-style="myObj">Welcome</h1>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.myObj = {
"color" : "white",
"background-color" : "coral",
"font-size" : "60px",
"padding" : "50px"
}
});
</script></body>
The
ng-style directive specifies the style attribute for the HTML element.
returning an object.
The object consists of CSS properties and values, in key value pairs.
<element ng-style="expression"></element>
Value
Description
expression
An expression which returns an object where the keys are CSS properties, and the values
are CSS values.
Created By www.ebooktutorials.in
ng-submit
Example
Run a function when the form is submitted:
<body ng-app="myApp" ng-controller="myCtrl">
<form ng-submit="myFunc()">
<input type="text">
<input type="submit">
</form>
<p>{{myTxt}}</p>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.myTxt = "You have not yet clicked submit";
$scope.myFunc = function () {
$scope.myTxt = "You clicked submit!";
}
});
</script></body>
The
submitted.
If the form does not have an
being submitted.
<form ng-submit="expression"></form>
Value
Description
expression
Created By www.ebooktutorials.in
ng-switch
Example
Show a section of HTML, only if it matches a certain value:
<div ng-switch="myVar">
<div ng-switch-when="dogs">
<h1>Dogs</h1>
<p>Welcome to a world of dogs.</p>
</div>
<div ng-switch-when="tuts">
<h1>Tutorials</h1>
<p>Learn from examples.</p>
</div>
<div ng-switch-when="cars">
<h1>Cars</h1>
<p>Read about cars.</p>
</div>
<div ng-switch-default>
<h1>Switch</h1>
<p>Select topic from the dropdown, to switch the content of this DIV.</p>
</div>
</div>
The
expression.
Child elements with the
Created By www.ebooktutorials.in
<element ng-switch="expression">
<element ng-switch-when="value"></element>
<element ng-switch-when="value"></element>
<element ng-switch-when="value"></element>
<element ng-switch-default></element>
</element>
Parameter Values
Value
Description
expression
ng-transclude
Specifies a point to insert transcluded elements.
Created By www.ebooktutorials.in
ng-value
Example
Set the value of the input field:
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-value="myVar">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.myVar = "Hello World!";
});
</script>
The
element.
<input ng-value="expression"></input>
Value
Description
expression
Created By www.ebooktutorials.in
Example
The link inside the AngularJS application will not reload the page:
<a href="">Click me!</a>
<div ng-app="">
<a href="">Click me too!</a>
</div>
Example
This form's "valid state" will not be consider "true", as long as the required input
field is empty:
<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>
<p>The forms's valid state is:</p>
<h1>{{myForm.$valid}}</h1>
Created By www.ebooktutorials.in
<form name="formname"></form>
Forms are being referred to by using the value of the name attribute.
Forms inside an AngularJS application are given certain classes. These classes
can be used to style forms according to their state.
The following classes are added:
Created By www.ebooktutorials.in
Example
Apply styles for unmodified (pristine) forms, and for modified forms:
<style>
form.ng-pristine {
background-color: lightblue;
}
form.ng-dirty {
background-color: pink;
}
</style>
Example
An input field with data-binding:
<input ng-model="myInput">
<p>The value of the input field is:</p>
<h1>{{myInput}}</h1>
Created By www.ebooktutorials.in
They provide data-binding, which means they are part of the AngularJS model,
and can be referred to, and updated, both in AngularJS functions and in the
DOM.
They provide validation. Example: an <input> element with
a required attribute, has the$valid state set to false as long as it is empty.
They also provide state control. AngularJS holds the current state of all input
elements.
Input fields have the following states:
The value of each state represents a Boolean value, and is either true or false.
<input ng-model="name">
Input elements are being referred to by using the value of the ngmodel attribute.
Created By www.ebooktutorials.in
Example
Apply styles for valid and invalid input elements, using standard CSS:
<style>
input.ng-invalid {
background-color: pink;
}
input.ng-valid {
background-color: lightgreen;
}
</style>
Created By www.ebooktutorials.in
Example
An textarea with data-binding:
<textarea ng-model="myTextarea"></textarea>
<p>The value of the textarea field is:</p>
<h1>{{myTextarea}}</h1>
The value of each state represents a Boolean value, and is either true of false.
Created By www.ebooktutorials.in
<textarea ng-model="name"></textarea>
Textarea elements are being referred to by using the value of the ngmodel attribute.
Example
Apply styles for valid and invalid textarea elements, using standard CSS:
<style>
textarea.ng-invalid {
background-color: pink;
}
textarea.ng-valid {
background-color: lightgreen;
}
</style>
Created By www.ebooktutorials.in
Example
Display the number as a currency format:
<div ng-app="myApp" ng-controller="costCtrl">
<p>Price = {{ price | currency }}</p>
</div>
Value
Description
symbol
fractionsize
Created By www.ebooktutorials.in
More Examples
Example
Display the price in the Norwegian currency format:
<div ng-app="myApp" ng-controller="costCtrl">
<p>Price = {{ price | currency : "NOK" }}</p>
</div>
Example
Display the price with three deciamls:
<div ng-app="myApp" ng-controller="costCtrl">
<p>Price = {{ price | currency : "NOK" : 3 }}</p>
</div>
Example
Display the number as a currency format:
<div ng-app="myApp" ng-controller="datCtrl">
<p>Date = {{ today | date }}</p>
</div>
Created By www.ebooktutorials.in
Value
Description
format
Optional. The date format to display the date in, which can be one or more of
the following:
"yyyy" year (2016)
"yy" year (16)
"y" year (2016)
"MMMM" month (January)
"MMM" month (Jan)
"MM" month (01)
"M" month (1)
"dd" day (06)
"d" day (6)
"EEEE" day (Tuesday)
"EEE" day (Tue)
"HH" hour, 00-23 (09)
"H" hour 0-23 (9)
"hh" hour in AM/PM, 00-12 (09)
"h" hour in AM/PM, 0-12 (9)
"mm" minute (05)
"m" minute (5)
"ss" second (05)
"s" second (5)
"sss" millisecond (035)
"a" (AM/PM)
"Z" timezone (from -1200 to +1200)
"ww" week (00-53)
"w" week (0-53)
"G" era (AD)
"GG" era (AD)
"GGG" era (AD)
"GGGG" era (Anno Domini)
The format value can also be one of the following predefined formats:
Created By www.ebooktutorials.in
Example
Display a date in a custom format:
<div ng-app="myApp" ng-controller="datCtrl">
<p>Date = {{ today | date :
"dd.MM.y" }}</p>
</div>
Example
Display a date using a predefined format:
<div ng-app="myApp" ng-controller="datCtrl">
<p>Date = {{ today | date : "fullDate" }}</p>
</div>
Created By www.ebooktutorials.in
Example
Display a date combination of text and a predefined format:
<div ng-app="myApp" ng-controller="datCtrl">
<p>Date = {{ today | date : "fullDate" }}</p>
</div>
Example
The date as a datetime string:
<div ng-app="">
<p>Date = {{ "2016-01-05T09:05:05.035Z" | date }}</p>
</div>
Example
Display the items that contains the letter "A":
<div ng-app="myApp" ng-controller="arrCtrl">
<ul>
<li ng-repeat="x in cars | filter : 'A'">{{x}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('arrCtrl', function($scope) {
$scope.cars = ["Aston Martin", "Audi", "Bentley", "BMW", "Bugatti"];
});
</script>
Created By www.ebooktutorials.in
The filter filter allows us to filter an array, and return an array containing
only the matching items.
This filter can only be used for arrays.
Value
Description
expression
The expression used when selecting items from the array. The expression can
be of type:
String: The array items that match the string will be returned.
Object: The object is a pattern to search for in the array. Example:{"name"
: "H", "city": "London"} will return the array items with a
name containing the letter "A", where the city contains the word "Berlin".
See example below.
Function: A function which will be called for each array item, and items where
the function returns true will be in the result array.
comparator
Optional. Defines how strict the comparison should be. The value can be:
true : Returns a match only if the value of the array item is exactly what we
compare it with.
false : Returns a match if the value of the array item contains what we
compare it with. This comparison is not case sensitiv. This is the default value.
function : A function where we can define what will be considered a match or
not.
Created By www.ebooktutorials.in
More Examples
Example
Use an object as a filter:
<div ng-app="myApp" ng-controller="arrCtrl">
<ul>
<li ng-repeat="x in customers | filter : {'name' : 'O', 'city' : 'London'}">
{{x.name + ", " + x.city}}
</li>
</ul></div>
<script>
var app = angular.module('myApp', []);
app.controller('arrCtrl', function($scope) {
$scope.customers = [
{"name" : "Alfreds Futterkiste", "city" : "Berlin"},
{"name" : "Around the Horn", "city" : "London"},
{"name" : "B's Beverages", "city" : "London"},
{"name" : "Bolido Comidas preparadas", "city" : "Madrid"},
{"name" : "Bon app", "city" : "Marseille"},
{"name" : "Bottom-Dollar Marketse" ,"city" : "Tsawassen"},
{"name" : "Cactus Comidas para llevar", "city" : "Buenos Aires"}
];
});</script>
Example
Do a "strict" comparison, which does not return a match unless the value
is exactly the same as the expression:
<div ng-app="myApp" ng-controller="arrCtrl">
<ul>
<li ng-repeat="x in customers | filter : 'London' : true">
{{x.name + ", " + x.city}}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('arrCtrl', function($scope) {
$scope.customers = [
{"name" : "London Food", "city" : "London"},
{"name" : "London Catering", "city" : "London City"},
{"name" : "London Travel", "city" : "Heathrow, London"}
];
});</script>
Created By www.ebooktutorials.in
Example
Display a JavaScript object as a JSON string:
<div ng-app="myApp" ng-controller="jsCtrl">
<h1>Customer:</h1>
<pre>{{customer | json}}</pre>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('jsCtrl', function($scope) {
$scope.customer = {
"name" : "Alfreds Futterkiste",
"city" : "Berlin",
"country" : "Germany"
};
});
</script>
Value
Description
spacing
Optional. A number specifying how many spaces to user per indentation. The
default value is 2
Created By www.ebooktutorials.in
More Examples
Example
Make sure that the JSON string is written with 12 spaces per indentation:
<div ng-app="myApp" ng-controller="jsCtrl">
<h1>Customer:</h1>
<pre>{{customer | json : 12}}</pre>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('jsCtrl', function($scope) {
$scope.customer = {
"name" : "Alfreds Futterkiste",
"city" : "Berlin",
"country" : "Germany"
};
});
</script>
Example
The JavaScript object as an array:
<div ng-app="myApp" ng-controller="jsCtrl">
<h1>Carnames:</h1>
<pre>{{cars | json}}</pre>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('jsCtrl', function($scope) {
$scope.cars = ["Audi", "BMW", "Ford"];
});
</script>
Created By www.ebooktutorials.in
Example
Display only the first three items of an array:
<div ng-app="myApp" ng-controller="sizeCtrl">
<ul>
<li ng-repeat="x in cars | limitTo : 3">{{x}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('sizeCtrl', function($scope) {
$scope.cars = ["Audi", "BMW", "Dodge", "Fiat", "Ford", "Volvo"];
});
</script>
Created By www.ebooktutorials.in
Value
Description
limit
begin
Example
Display the last three items of the array:
<div ng-app="myApp" ng-controller="sizeCtrl">
<ul>
<li ng-repeat="x in cars | limitTo : -3">{{x}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('sizeCtrl', function($scope) {
$scope.cars = ["Audi", "BMW", "Dodge", "Fiat", "Ford", "Volvo"];
});
</script>
Example
Display three items, starting at position 1:
<div ng-app="myApp" ng-controller="sizeCtrl">
<ul>
<li ng-repeat="x in cars | limitTo : 3 : 1">{{x}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('sizeCtrl', function($scope) {
$scope.cars = ["Audi", "BMW", "Dodge", "Fiat", "Ford", "Volvo"];
});
</script>
Created By www.ebooktutorials.in
Example
Display the first three characters of the string:
<div ng-app="myApp" ng-controller="sizeCtrl">
<h1>{{txt | limitTo : 3}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('sizeCtrl', function($scope) {
$scope.txt = "Hello, welcome to AngularJS";
});
</script>
Example
Display the first three digits og the number:
<div ng-app="myApp" ng-controller="sizeCtrl">
<h1>{{phone | limitTo : 3}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('sizeCtrl', function($scope) {
$scope.phone = "123456789";
});
</script>
Created By www.ebooktutorials.in
Example
Display the text in lowercase letters:
<div ng-app="myApp" ng-controller="caseCtrl">
<h1>{{txt | lowercase}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('caseCtrl', function($scope) {
$scope.txt = "Hello World!";
});
</script>
{{ string | lowercase }}
Created By www.ebooktutorials.in
Example
Format the prize as a number::
<div ng-app="myApp" ng-controller="nCtrl">
<h1>{{prize | number}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('nCtrl', function($scope) {
$scope.prize = 1000000;
});
</script>
Created By www.ebooktutorials.in
Value
Description
fractionsize
Example
Display the weight with 3 decimals:
<div ng-app="myApp" ng-controller="nCtrl">
<h1>{{weight | number : 3}} kg</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('nCtrl', function($scope) {
$scope.weight = 9999;
});
</script>
Created By www.ebooktutorials.in
Example
Display the items alphabetically:
<div ng-app="myApp" ng-controller="orderCtrl">
<ul>
<li ng-repeat="x in cars | orderBy">{{x}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('orderCtrl', function($scope) {
$scope.cars = ["Dodge", "Fiat", "Audi", "Volvo", "BMW", "Ford"];
});
</script>
Created By www.ebooktutorials.in
Value
Description
expression
The expression used to determine the order. The expression can be of type:
String: If the array is an array of objects, you can sort the array by the value of
one of the object properties. See the examples below.
Function: You can create a function to organize the sorting.
Array: Use an array if you need more than one object property to determine
the sorting order. The array items can be both strings and functions.
reverse
Optional. Set to true if you want to reverse the order of the array.
Example
Sort the array by "city":
<div ng-app="myApp" ng-controller="orderCtrl">
<ul>
<li ng-repeat="x in customers | orderBy : 'city'">{{x.name + ", " +
x.city}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('orderCtrl', function($scope) {
$scope.customers = [
{"name" : "Bottom-Dollar Marketse" ,"city" : "Tsawassen"},
{"name" : "Alfreds Futterkiste", "city" : "Berlin"},
{"name" : "Bon app", "city" : "Marseille"},
{"name" : "Cactus Comidas para llevar", "city" : "Buenos Aires"},
{"name" : "Bolido Comidas preparadas", "city" : "Madrid"},
{"name" : "Around the Horn", "city" : "London"},
{"name" : "B's Beverages", "city" : "London"}
];
});
</script>
Created By www.ebooktutorials.in
Example
Sort the array by "city", in descending order:
<div ng-app="myApp" ng-controller="orderCtrl">
<ul>
<li ng-repeat="x in customers | orderBy : '-city'">{{x.name + ", " +
x.city}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('orderCtrl', function($scope) {
$scope.customers = [
{"name" : "Bottom-Dollar Marketse" ,"city" : "Tsawassen"},
{"name" : "Alfreds Futterkiste", "city" : "Berlin"},
{"name" : "Bon app", "city" : "Marseille"},
{"name" : "Cactus Comidas para llevar", "city" : "Buenos Aires"},
{"name" : "Bolido Comidas preparadas", "city" : "Madrid"},
{"name" : "Around the Horn", "city" : "London"},
{"name" : "B's Beverages", "city" : "London"}
];
});
</script>
Created By www.ebooktutorials.in
Example
Display the text in uppercase letters:
<div ng-app="myApp" ng-controller="caseCtrl">
<h1>{{txt | uppercase}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('caseCtrl', function($scope) {
$scope.txt = "Hello World!";
});
</script>
{{ string | uppercase}}
Created By www.ebooktutorials.in
$dirty
$invalid
$error
API
Description
angular.lowercase()
angular.forEach()
Created By www.ebooktutorials.in
API
Description
angular.isArray()
angular.isDate()
angular.isDefined()
angular.isElement()
angular.isFunction()
angular.isNumber()
angular.isObject()
angular.isString()
Created By www.ebooktutorials.in
API
Description
API
Description
angular.module()