AngularJS Tutorial W3Schools PDF
AngularJS Tutorial W3Schools PDF
W3SCHOOLS.com
This Tutorial
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:
In every chapter, you can edit the examples online, and click on a button to view the result.
AngularJS Example
<!DOCTYPE html>
<html lang="en-US">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
</div>
</body>
</html>
1
What You Should Already Know
Before you study AngularJS, you should have a basic understanding of:
HTML
CSS
JavaScript
AngularJS History
The idea turned out very well, and the project is now officially supported by Google.
AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.
AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.
AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
AngularJS Example
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/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>
2
Example explained:
The ng-app directive tells AngularJS that the <div> element is the "owner" of an AngularJS
application.
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 variable name.
AngularJS Directives
As you have already seen, AngularJS directives are HTML attributes with an ng prefix.
AngularJS Example
</div>
AngularJS Example
</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.
AngularJS Expressions
AngularJS expressions are written inside double braces: {{ expression }}.
AngularJS Example
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
3
</div>
</body>
</html>
AngularJS expressions bind AngularJS data to HTML the same way as the ng-bind directive.
AngularJS Example
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p>{{name}}</p>
</div>
</body>
</html>
AngularJS Applications
AngularJS modules define AngularJS applications.
The ng-app directive defines the application, the ng-controller directive defines the controller.
AngularJS Example
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>
AngularJS Module
4
AngularJS controllers control applications:
AngularJS Controller
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
You will learn more about modules and controllers later in this tutorial.
AngularJS Expressions
AngularJS binds data to HTML using Expressions.
AngularJS Expressions
AngularJS expressions binds data to HTML the same way as the ng-bind directive.
AngularJS expressions are much like JavaScript expressions: They can contain literals, operators,
and variables.
AngularJS Example
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>
If you remove the ng-app directive, HTML will display the expression as it is, without solving it:
AngularJS Example
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div>
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>
5
AngularJS Numbers
AngularJS Example
</div>
AngularJS Example
</div>
Using ng-init is not very common. You will learn a better way to initialize data in the chapter
about controllers.
AngularJS Strings
AngularJS Example
</div>
AngularJS Example
</div>
AngularJS Objects
AngularJS Example
6
</div>
AngularJS Example
</div>
AngularJS Arrays
AngularJS Example
</div>
AngularJS Example
</div>
Like JavaScript expressions, AngularJS expressions can contain literals, operators, and variables.
AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript
expressions do.
AngularJS Directives
AngularJS lets you extend HTML with new attributes called Directives.
AngularJS Directives
AngularJS directives are extended HTML attributes with the prefix ng-.
7
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
AngularJS Example
</div>
The ng-app directive also tells AngularJS that the <div> element is the "owner" of the AngularJS
application.
Data Binding
The {{ firstName }} expression, in the example above, is an AngularJS data binding expression.
In the next example two text fields are synchronized with two ng-model directives:
AngularJS Example
</div>
Using ng-init is not very common. You will learn how to initialize data in the chapter about
controllers.
AngularJS Example
AngularJS Example
8
<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>
AngularJS is perfect for database CRUD (Create Read Update Delete) applications.
Just imagine if these objects were records from a database.
The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is
loaded.
Later you will learn how ng-app can have a value (like ng-app="myModule"), to connect code
modules.
Normally, you will not use ng-init. You will use a controller or module instead.
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
The ng-repeat directive clones HTML elements once for each item in a collection (in an array).
AngularJS Controllers
AngularJS controllers control the data of AngularJS applications.
9
AngularJS controllers are regular JavaScript Objects.
AngularJS Controllers
AngularJS Example
</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>.
In AngularJS, $scope is the application object (the owner of application variables and functions).
The controller creates two properties (variables) in the scope (firstName and lastName).
The ng-model directives bind the input fields to the controller properties (firstName and lastName).
Controller Methods
The example above demonstrated a controller object with two properties: lastName and firstName.
AngularJS Example
10
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>
Just copy the code between the <script> tags into an external file named personController.js:
AngularJS Example
</div>
<script src="personController.js"></script>
Another Example
AngularJS Example
<ul>
<li ng-repeat="x in names">
11
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
<script src="namesController.js"></script>
AngularJS Filters
Filters can be added to expressions and directives using a pipe character.
AngularJS Filters
Filter Description
currency Format a number to a currency format.
filter Select a subset of items from an array.
lowercase Format a string to lower case.
orderBy Orders an array by an expression.
uppercase Format a string to upper case.
A filter can be added to an expression with a pipe character (|) and a filter.
(For the next two examples we will use the person controller from the previous chapter)
AngularJS Example
</div>
AngularJS Example
</div>
AngularJS Example
12
<div ng-app="myApp" ng-controller="costCtrl">
</div>
A filter can be added to a directive with a pipe character (|) and a filter.
AngularJS Example
<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>
<div>
Filtering Input
An input filter can be added to a directive with a pipe character (|) and filter followed by a colon and a
model name.
AngularJS Example
<ul>
<li ng-repeat="x in names | filter:test | orderBy:'country'">
{{ (x.name | uppercase) + ', ' + x.country }}
</li>
</ul>
</div>
Providing Data
http://www.w3schools.com/angular/customers.php
13
{
"records": [
{
"Name" : "Alfreds Futterkiste",
"City" : "Berlin",
"Country" : "Germany"
},
{
"Name" : "Berglunds snabbkp",
"City" : "Lule",
"Country" : "Sweden"
},
{
"Name" : "Centro comercial Moctezuma",
"City" : "Mxico D.F.",
"Country" : "Mexico"
},
{
"Name" : "Ernst Handel",
"City" : "Graz",
"Country" : "Austria"
},
{
"Name" : "FISSA Fabrica Inter. Salchichas S.A.",
"City" : "Madrid",
"Country" : "Spain"
},
{
"Name" : "Galera del gastrnomo",
"City" : "Barcelona",
"Country" : "Spain"
},
{
"Name" : "Island Trading",
"City" : "Cowes",
"Country" : "UK"
},
{
"Name" : "Kniglich Essen",
"City" : "Brandenburg",
"Country" : "Germany"
},
{
"Name" : "Laughing Bacchus Wine Cellars",
"City" : "Vancouver",
"Country" : "Canada"
},
{
"Name" : "Magazzini Alimentari Riuniti",
"City" : "Bergamo",
"Country" : "Italy"
},
{
"Name" : "North/South",
"City" : "London",
"Country" : "UK"
},
{
"Name" : "Paris spcialits",
"City" : "Paris",
14
"Country" : "France"
},
{
"Name" : "Rattlesnake Canyon Grocery",
"City" : "Albuquerque",
"Country" : "USA"
},
{
"Name" : "Simons bistro",
"City" : "Kbenhavn",
"Country" : "Denmark"
},
{
"Name" : "The Big Cheese",
"City" : "Portland",
"Country" : "USA"
},
{
"Name" : "Vaffeljernet",
"City" : "rhus",
"Country" : "Denmark"
},
{
"Name" : "Wolski Zajazd",
"City" : "Warszawa",
"Country" : "Poland"
}
]
}
AngularJS $http
AngularJS $http is a core service for reading data from web servers.
AngularJS Example
<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function(response) {$scope.names = response.records;});
});
</script>
Application explained:
The AngularJS application is defined by ng-app. The application runs inside a <div>.
15
The ng-controller directive names the controller object.
$scope is the application object (the owner of application variables and functions).
If success, the controller creates a property (names) in the scope, with JSON data from the server.
ngularJS Tables
The ng-repeat directive is perfect for displaying tables.
AngularJS Example
<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")
.success(function (response) {$scope.names = response.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;
16
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
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>
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>
17
</tr>
</table>
AngularJS SQL
The code from the previous chapter can also be used to read from databases.
AngularJS Example
<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")
.success(function (response) {$scope.names = response.records;});
});
</script>
AngularJS Example
<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")
.success(function (response) {$scope.names = response.records;});
});
</script>
The following section is a listing of the server code used to fetch SQL data.
18
2. Using PHP and MS Access. Returning JSON.
3. Using ASP.NET, VB, and MS Access. Returning JSON.
4. Using ASP.NET, Razor, and SQL Lite. Returning JSON.
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");
$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);
?>
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=ISO-8859-1");
$outp = "";
while (!$rs->EOF) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"Name":"' . $rs["CompanyName"] . '",';
$outp .= '"City":"' . $rs["City"] . '",';
19
$outp .= '"Country":"'. $rs["Country"] . '"}';
$rs->MoveNext();
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo ($outp);
?>
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 + ","
20
outp = outp + c + "Country" + c + ":" + c + @row.Country + c + "}"
}
outp ="{" + c + "records" + c + ":[" + outp + "]}"
@outp
The ng-disabled directive binds AngularJS application data to the disabled attribute of HTML
elements.
AngularJS Example
<p>
<button ng-disabled="mySwitch">Click Me!</button>
</p>
<p>
<input type="checkbox" ng-model="mySwitch">Button
</p>
</div>
Application explained:
The ng-disabled directive binds the application data mySwitch to the HTML button's disabled
attribute.
The ng-model directive binds the value of the HTML checkbox element to the value of mySwitch.
<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="">
21
<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.
AngularJS Example
<div ng-app="">
</div>
In the next chapter, there are more examples, using the click of a button to hide HTML
elements.
AngularJS Example
<div ng-app="">
</div>
AngularJS Events
AngularJS has its own HTML events directives.
AngularJS Example
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
22
});
</script>
The ng-hide directive can be used to set the visibility of a part of an application.
AngularJS Example
<button ng-click="toggle()">Toggle</button>
<p ng-hide="myVar">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John",
$scope.lastName = "Doe"
$scope.myVar = false;
$scope.toggle = function() {
$scope.myVar = !$scope.myVar;
};
});
</script>
Application explained:
The first part of the personController is the same as in the chapter about controllers.
The ng-hide directive sets the visibility, of a <p> element with two input fields, according to the value
(true or false) of myVar.
The ng-show directive can also be used to set the visibility of a part of an application.
23
The value ng-show="true" makes the element visible.
AngularJS Example
<button ng-click="toggle()">Toggle</button>
<p ng-show="myVar">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John",
$scope.lastName = "Doe"
$scope.myVar = true;
$scope.toggle = function() {
$scope.myVar = !$scope.myVar;
};
});
</script>
AngularJS Modules
An AngularJS module defines an application.
AngularJS Example
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<script>
24
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
It is common in AngularJS applications to put the module and the controllers in JavaScript files.
In this example, "myApp.js" contains an application module definition, while "myCtrl.js" contains the
controller:
AngularJS Example
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<script src="myApp.js"></script>
<script src="myCtrl.js"></script>
</body>
</html>
myApp.js
The [] parameter in the module definition can be used to define dependent modules.
myCtrl.js
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName= "Doe";
});
Global functions should be avoided in JavaScript. They can easily be overwritten or destroyed by other
scripts.
AngularJS modules reduces this problem, by keeping all functions local to the module.
25
While it is common in HTML applications to place scripts at the end of the <body> element, it is
recommended that you load the AngularJS library either in the <head> or at the start of the <body>.
This is because calls to angular.module can only be compiled after the library has been loaded.
AngularJS Example
<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
AngularJS Forms
An AngularJS form is a collection of input controls.
HTML Controls
input elements
select elements
button elements
textarea elements
HTML Forms
First Name:
Last Name:
form = {"firstName":"John","lastName":"Doe"}
master = {"firstName":"John","lastName":"Doe"}
26
Application Code
<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>
The novalidate attribute is new in HTML5. It disables any default browser validation.
Example Explained
The ng-model directive binds two input elements to the user object in the model.
The formCtrl function sets initial values to the master object, and defines the reset() method.
The reset() method sets the user object equal to the master object.
The ng-click directive invokes the reset() method, only if the button is clicked.
The novalidate attribute is not needed for this application, but normally you will use it in AngularJS
forms, to override standard HTML5 validation.
Input Validation
In the previous chapter, you learned about AngularJS forms and controls.
AngularJS forms and controls can provide validation services, and notify users of invalid input.
27
Client-side validation cannot alone secure user input. Server side validation is also necessary.
Application Code
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<h2>Validation Example</h2>
<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">
</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 HTML form attribute novalidate is used to disable default browser validation.
Example Explained
The AngularJS directive ng-model binds the input elements to the model.
28
Because of ng-show, the spans with color:red are displayed only when user or email is $dirty and
$invalid.
Property Description
$dirty The user has interacted with the field.
$valid The field content is valid.
$invalid The field content is invalid.
$pristine User has not interacted with the field yet.
AngularJS API
API stands for Application Programming Interface.
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.
API Description
angular.lowercase() Converts a string to lowercase
angular.uppercase() Converts a string to uppercase
angular.isString() Returns true if the reference is a string
angular.isNumber() Returns true if the reference is a number
angular.lowercase()
Example
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.x1 = "JOHN";
$scope.x2 = angular.lowercase($scope.x1);
});
</script>
angular.uppercase()
Example
29
<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>
angular.isString()
Example
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.x1 = "JOHN";
$scope.x2 = angular.isString($scope.x1);
});
</script>
angular.isNumber()
Example
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.x1 = "JOHN";
$scope.x2 = angular.isNumber($scope.x1);
});
</script>
Bootstrap
To include Bootstrap in your AngularJS application, add the following line to the head of your
document:
30
If you want to study Bootstrap, visit our Bootstrap Tutorial.
Below is a complete HTML example, with all AngularJS directives and Bootstrap classes explained.
HTML Code
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="myApp" ng-controller="userCtrl">
<div class="container">
<h3>Users</h3>
<hr>
<button class="btn btn-success" ng-click="editUser('new')">
<span class="glyphicon glyphicon-user"></span> Create New User
</button>
<hr>
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">First Name:</label>
<div class="col-sm-10">
<input type="text" ng-model="fName" ng-disabled="!edit" placeholder="First Name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Last Name:</label>
<div class="col-sm-10">
<input type="text" ng-model="lName" ng-disabled="!edit" placeholder="Last Name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Password:</label>
<div class="col-sm-10">
<input type="password" ng-model="passw1" placeholder="Password">
</div>
31
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Repeat:</label>
<div class="col-sm-10">
<input type="password" ng-model="passw2" placeholder="Repeat Password">
</div>
</div>
</form>
<hr>
<button class="btn btn-success" ng-disabled="error || incomplete">
<span class="glyphicon glyphicon-save"></span> Save Changes
</button>
</div>
JavaScript Code
myUsers.js
32
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.editUser = function(id) {
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.test();});
$scope.$watch('passw2',function() {$scope.test();});
$scope.$watch('fName', function() {$scope.test();});
$scope.$watch('lName', function() {$scope.test();});
$scope.test = function() {
if ($scope.passw1 !== $scope.passw2) {
$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;
}
};
});
33
$scope.users Model variable (array of users)
$scope.edit Set to true when user clicks on create user.
$scope.error Set to true if passw1 not equal passw2
$scope.incomplete Set to true if any field is empty (length = 0)
$scope.editUser Sets model variables
$scope.$watch Watches model variables
$scope.test Tests model variables for errors and incompleteness
AngularJS Includes
With AngularJS, you can include HTML files in HTML.
Including a portion of HTML in HTML is, unfortunately, not (yet) supported by HTML.
With SSI, you can include HTML in HTML before the page is sent to the browser.
PHP Example
The most common way is to use an http request (AJAX) to fetch data from a server, and then write the
data to the innerHTML of an HTML element.
With AngularJS, you can include HTML content using the ng-include directive:
Example
<body>
<div class="container">
<div ng-include="'myUsers_List.htm'"></div>
<div ng-include="'myUsers_Form.htm'"></div>
</div>
</body>
34
Step 1: Create the HTML List
myUsers_List.htm
<h3>Users</h3>
myUsers_Form.htm
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">First Name:</label>
<div class="col-sm-10">
<input type="text" ng-model="fName" ng-disabled="!edit" placeholder="First Name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Last Name:</label>
<div class="col-sm-10">
<input type="text" ng-model="lName" ng-disabled="!edit" placeholder="Last Name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Password:</label>
<div class="col-sm-10">
<input type="password" ng-model="passw1" placeholder="Password">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Repeat:</label>
<div class="col-sm-10">
<input type="password" ng-model="passw2" placeholder="Repeat Password">
</div>
35
</div>
</form>
<hr>
<button class="btn btn-success" ng-disabled="error || incomplete">
<span class="glyphicon glyphicon-save"></span> Save Changes
</button>
myUsers.js
$scope.$watch('passw1',function() {$scope.test();});
$scope.$watch('passw2',function() {$scope.test();});
$scope.$watch('fName',function() {$scope.test();});
$scope.$watch('lName',function() {$scope.test();});
$scope.test = function() {
if ($scope.passw1 !== $scope.passw2) {
$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;
}
};
})
36
Step 4: Create the Main Page
<!DOCTYPE html>
<html>
<link rel="stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<div class="container">
<div ng-include="'myUsers_List.htm'"></div>
<div ng-include="'myUsers_Form.htm'"></div>
</div>
</body>
</html>
AngularJS Application
It is time to create a real AngularJS Single Page Application (SPA).
You have learned more than enough to create your first AngularJS application:
My Note
Application Explained
AngularJS Example
<html ng-app="myNoteApp">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-controller="myNoteCtrl">
<h2>My Note</h2>
37
<p><textarea ng-model="message" cols="40" rows="10"></textarea></p>
<p>
<button ng-click="save()">Save</button>
<button ng-click="clear()">Clear</button>
</p>
</div>
<script src="myNoteApp.js"></script>
<script src="myNoteCtrl.js"></script>
</body>
</html>
app.controller("myNoteCtrl", function($scope) {
$scope.message = "";
$scope.left = function() {return 100 - $scope.message.length;};
$scope.clear = function() {$scope.message = "";};
$scope.save = function() {alert("Note Saved");};
});
<html ng-app="myNoteApp">
<div ng-controller="myNoteCtrl">
The two ng-click events invoke the controller functions clear() and save():
<button ng-click="save()">Save</button>
<button ng-click="clear()">Clear</button>
An ng-bind directive binds the controller function left() to a <span> displaying the characters left:
Your application libraries are added to the page (after the library):
<script src="myNoteApp.js"></script>
<script src="myNoteCtrl.js"></script>
38
AngularJS Application Skeleton
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 (ng-app=).
For single page applications (SPA), the root of the application is often the <html> element.
One or more ng-controller directives define the application controllers. Each controller has its own
scope: the HTML element where they were defined.
The root of the application can be the whole page, or a smaller portion of the page. The smaller the
portion, the faster the application will compile and execute.
AngularJS Examples
Try it Yourself
You can edit the examples online, and click on a button to view the result.
AngularJS Example
<div ng-app="">
</div>
AngularJS Basics
AngularJS Expressions
39
A simple Expression
Expression without ng-app
Expression with Numbers
Using ng-bind with Numbers
Expression with Strings
Using ng-bind with Strings
Expression with Objects
Using ng-bind with Objects
Expression with Arrays
Using ng-bind with Arrays
Expressions Explained
AngularJS Directives
AngularJS Directives
The ng-model Directive
The ng-repeat Directive (with Arrays)
The ng-repeat Directive (with Objects)
Directives Explained
AngularJS Controllers
AngularJS Controller
Controller Properties
Controller Functions
Controller in JavaScript File I
Controller in JavaScript File II
Controllers Explained
AngularJS Filters
Filters Explained
AngularJS XMLHttpRequest
XMLHttpRequest Explained
AngularJS Tables
40
Tables Explained
AngularJS Events
AngularJS Modules
AngularJS Forms
AngularJS Forms
AngularJS Validation
AngularJS API
AngularJS angular.lowercase()
AngularJS angular.uppercase()
AngularJS angular.isString()
AngularJS angular.isNumber()
API Explained
AngularJS Bootstrap
Bootstrap Explained
AngularJS Applications
41
AngularJS Note Application
AngularJS ToDo Application
AngularJS Applications
AngularJS Directives
AngularJS Filters
Filter Description
currency Format a number to a currency format.
filter Select a subset of items from an array.
lowercase Format a string to lower case.
orderBy Orders an array by an expression.
uppercase Format a string to upper case.
AngularJS Events
ng-click
ng-dbl-click
ng-mousedown
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-keydown
ng-keyup
ng-keypress
ng-change
42
AngularJS Validation Properties
$dirty
$invalid
$error
Converting
API Description
angular.lowercase() Converts a string to lowercase
angular.uppercase() Converts a string to uppercase
angular.copy() Creates a deep copy of an object or an array
angular.forEach() Executes a function for each element in an object or array
Comparing
API Description
angular.isArray() Returns true if the reference is an array
angular.isDate() Returns true if the reference is a date
angular.isDefined() Returns true if the reference is defined
angular.isElement() Returns true if the reference is a DOM element
angular.isFunction() Returns true if the reference is a function
angular.isNumber() Returns true if the reference is a number
angular.isObject() Returns true if the reference is an object
angular.isString() Returns true if the reference is a string
angular.isUndefined() Returns true if the reference is undefined
angular.equals() Returns true if two references are equal
JSON
API Description
angular.fromJSON() Deserializes a JSON string
angular.toJSON() Serializes a JSON string
Basic
API Description
angular.bootstrap() Starts AngularJS manually
angular.element() Wraps an HTML element as an jQuery element
angular.module() Creates, registers, or retrieves an AngularJS module
43