AngularJS Tutorial. ¶
AngularJS version 1.0 was released in 2012. Miško 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.
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.
What You Should Already Know ¶
Before you study AngularJS, you should have a basic understanding of:
- HTML
- CSS
- JavaScript
1// AngularJS is a JavaScript framework. It is a library written in JavaScript.
2// AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:
3// <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
4
5///////////////////////////////////
6// AngularJS Extends HTML
7
8//AngularJS extends HTML with ng-directives.
9//The ng-app directive defines an AngularJS application.
10//The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
11//The ng-bind directive binds application data to the HTML view.
12<!DOCTYPE html>
13<html>
14 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
15 <body>
16 <div ng-app="">
17 <p>Name: <input type="text" ng-model="name"></p>
18 <p ng-bind="name"></p>
19 </div>
20 </body>
21</html>
22
23/*
24 * Example explained:
25 * AngularJS starts automatically when the web page has loaded.
26 * The ng-app directive tells AngularJS that the <div> element is the "owner" of an AngularJS application.
27 * The ng-model directive binds the value of the input field to the application variable name.
28 * The ng-bind directive binds the innerHTML of the <p> element to the application variable name.
29*/
30<tag> Here are content to be interpreted </tag>
31
32///////////////////////////////////
33// AngularJS Expressions
34
35// AngularJS expressions are written inside double braces: {{ expression }}.
36// AngularJS expressions binds data to HTML the same way as the ng-bind directive.
37// AngularJS will "output" data exactly where the expression is written.
38// AngularJS expressions are much like JavaScript expressions: They can contain literals, operators, and variables.
39// Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}
40<!DOCTYPE html>
41<html>
42 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
43 <body>
44 <div ng-app="">
45 <p>My first expression: {{ 5 + 5 }}</p>
46 </div>
47 </body>
48</html>
49
50//If you remove the ng-app directive, HTML will display the expression as it is, without solving it:
51<!DOCTYPE html>
52<html>
53 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
54 <body>
55 <div>
56 <p>My first expression: {{ 5 + 5 }}</p>
57 </div>
58 </body>
59</html>
60
61// AngularJS expressions bind AngularJS data to HTML the same way as the ng-bind directive.
62<!DOCTYPE html>
63<html>
64<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
65 <body>
66 <div ng-app="">
67 <p>Name: <input type="text" ng-model="name"></p>
68 <p>{{name}}</p>
69 </div>
70 </body>
71</html>
72
73// AngularJS numbers are like JavaScript numbers:
74<div ng-app="" ng-init="quantity=1;cost=5">
75 <p>Total in dollar: {{ quantity * cost }}</p>
76</div>
77
78//AngularJS strings are like JavaScript strings:
79<div ng-app="" ng-init="firstName='John';lastName='Doe'">
80 <p>The name is <span ng-bind="firstName + ' ' + lastName"></span></p>
81</div>
82
83//AngularJS objects are like JavaScript objects:
84<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
85 <p>The name is {{ person.lastName }}</p>
86</div>
87
88//AngularJS arrays are like JavaScript arrays:
89<div ng-app="" ng-init="points=[1,15,19,2,40]">
90 <p>The third result is {{ points[2] }}</p>
91</div>
92
93// Like JavaScript expressions, AngularJS expressions can contain literals, operators, and variables.
94// Unlike JavaScript expressions, AngularJS expressions can be written inside HTML.
95// AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do.
96// AngularJS expressions support filters, while JavaScript expressions do not.
97
98///////////////////////////////////
99// AngularJS Directives
100
101
102//AngularJS directives are extended HTML attributes with the prefix ng-.
103//The ng-app directive initializes an AngularJS application.
104//The ng-init directive initializes application data.
105//The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
106<div ng-app="" ng-init="firstName='John'">
107 <p>Name: <input type="text" ng-model="firstName"></p>
108 <p>You wrote: {{ firstName }}</p>
109</div>
110
111//Using ng-init is not very common. You will learn how to initialize data in the chapter about controllers.
112
113//The ng-repeat directive repeats an HTML element:
114<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
115 <ul>
116 <li ng-repeat="x in names">
117 {{ x }}
118 </li>
119 </ul>
120</div>
121
122//The ng-repeat directive used on an array of objects:
123<div ng-app="" ng-init="names=[
124{name:'Jani',country:'Norway'},
125{name:'Hege',country:'Sweden'},
126{name:'Kai',country:'Denmark'}]">
127 <ul>
128 <li ng-repeat="x in names">
129 {{ x.name + ', ' + x.country }}
130 </li>
131 </ul>
132</div>
133
134// AngularJS is perfect for database CRUD (Create Read Update Delete) applications.
135// Just imagine if these objects were records from a database.
136
137// The ng-app directive defines the root element of an AngularJS application.
138// The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded.
139// Later you will learn how ng-app can have a value (like ng-app="myModule"), to connect code modules.
140
141// The ng-init directive defines initial values for an AngularJS application.
142// Normally, you will not use ng-init. You will use a controller or module instead.
143// You will learn more about controllers and modules later.
144
145//The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
146//The ng-model directive can also:
147//Provide type validation for application data (number, email, required).
148//Provide status for application data (invalid, dirty, touched, error).
149//Provide CSS classes for HTML elements.
150//Bind HTML elements to HTML forms.
151
152//The ng-repeat directive clones HTML elements once for each item in a collection (in an array).
153
154///////////////////////////////////
155// AngularJS Controllers
156
157// AngularJS controllers control the data of AngularJS applications.
158// AngularJS controllers are regular JavaScript Objects.
159
160// AngularJS applications are controlled by controllers.
161// The ng-controller directive defines the application controller.
162// A controller is a JavaScript Object, created by a standard JavaScript object constructor.
163
164<div ng-app="myApp" ng-controller="myCtrl">
165
166First Name: <input type="text" ng-model="firstName"><br>
167Last Name: <input type="text" ng-model="lastName"><br>
168<br>
169Full Name: {{firstName + " " + lastName}}
170
171</div>
172
173<script>
174var app = angular.module('myApp', []);
175app.controller('myCtrl', function($scope) {
176 $scope.firstName = "John";
177 $scope.lastName = "Doe";
178});
179</script>
180
181//Application explained:
182
183//The AngularJS application is defined by ng-app="myApp". The application runs inside the <div>.
184//The ng-controller="myCtrl" attribute is an AngularJS directive. It defines a controller.
185//The myCtrl function is a JavaScript function.
186//AngularJS will invoke the controller with a $scope object.
187//In AngularJS, $scope is the application object (the owner of application variables and functions).
188//The controller creates two properties (variables) in the scope (firstName and lastName).
189//The ng-model directives bind the input fields to the controller properties (firstName and lastName).
190
191//The example above demonstrated a controller object with two properties: lastName and firstName.
192//A controller can also have methods (variables as functions):
193<div ng-app="myApp" ng-controller="personCtrl">
194
195First Name: <input type="text" ng-model="firstName"><br>
196Last Name: <input type="text" ng-model="lastName"><br>
197<br>
198Full Name: {{fullName()}}
199
200</div>
201
202<script>
203var app = angular.module('myApp', []);
204app.controller('personCtrl', function($scope) {
205 $scope.firstName = "John";
206 $scope.lastName = "Doe";
207 $scope.fullName = function() {
208 return $scope.firstName + " " + $scope.lastName;
209 }
210});
211</script>
212
213//In larger applications, it is common to store controllers in external files.
214//Just copy the code between the <script> </script> tags into an external file named personController.js:
215
216<div ng-app="myApp" ng-controller="personCtrl">
217
218First Name: <input type="text" ng-model="firstName"><br>
219Last Name: <input type="text" ng-model="lastName"><br>
220<br>
221Full Name: {{firstName + " " + lastName}}
222
223</div>
224
225<script src="personController.js"></script>
226
227// For the next example we will create a new controller file:
228angular.module('myApp', []).controller('namesCtrl', function($scope) {
229 $scope.names = [
230 {name:'Jani',country:'Norway'},
231 {name:'Hege',country:'Sweden'},
232 {name:'Kai',country:'Denmark'}
233 ];
234});
235
236//Save the file as namesController.js:
237//And then use the controller file in an application:
238
239<div ng-app="myApp" ng-controller="namesCtrl">
240
241<ul>
242 <li ng-repeat="x in names">
243 {{ x.name + ', ' + x.country }}
244 </li>
245</ul>
246
247</div>
248
249<script src="namesController.js"></script>
250
251///////////////////////////////////
252// AngularJS Filters
253
254// Filters can be added to expressions and directives using a pipe character.
255// AngularJS filters can be used to transform data:
256
257- **currency**: Format a number to a currency format.
258- **filter**: Select a subset of items from an array.
259- **lowercase**: Format a string to lower case.
260- **orderBy**: Orders an array by an expression.
261- **uppercase**: Format a string to upper case.
262
263//A filter can be added to an expression with a pipe character (|) and a filter.
264//(For the next two examples we will use the person controller from the previous chapter)
265//The uppercase filter format strings to upper case:
266<div ng-app="myApp" ng-controller="personCtrl">
267
268<p>The name is {{ lastName | uppercase }}</p>
269
270</div>
271
272//The lowercase filter format strings to lower case:
273<div ng-app="myApp" ng-controller="personCtrl">
274
275<p>The name is {{ lastName | lowercase }}</p>
276
277</div>
278
279//The currency filter formats a number as currency:
280<div ng-app="myApp" ng-controller="costCtrl">
281
282<input type="number" ng-model="quantity">
283<input type="number" ng-model="price">
284
285<p>Total = {{ (quantity * price) | currency }}</p>
286
287</div>
288
289//A filter can be added to a directive with a pipe character (|) and a filter.
290//The orderBy filter orders an array by an expression:
291<div ng-app="myApp" ng-controller="namesCtrl">
292
293<ul>
294 <li ng-repeat="x in names | orderBy:'country'">
295 {{ x.name + ', ' + x.country }}
296 </li>
297</ul>
298
299<div>
300
301//An input filter can be added to a directive with a pipe character (|)
302//and filter followed by a colon and a model name.
303//The filter selects a subset of an array:
304
305<div ng-app="myApp" ng-controller="namesCtrl">
306
307<p><input type="text" ng-model="test"></p>
308
309<ul>
310 <li ng-repeat="x in names | filter:test | orderBy:'country'">
311 {{ (x.name | uppercase) + ', ' + x.country }}
312 </li>
313</ul>
314
315</div>
316
317///////////////////////////////////
318// AngularJS AJAX - $http
319
320//$http is an AngularJS service for reading data from remote servers.
321
322// The following data can be provided by a web server:
323// http://www.w3schools.com/angular/customers.php
324// **Check the URL to see the data format**
325
326// AngularJS $http is a core service for reading data from web servers.
327// $http.get(url) is the function to use for reading server data.
328<div ng-app="myApp" ng-controller="customersCtrl">
329
330<ul>
331 <li ng-repeat="x in names">
332 {{ x.Name + ', ' + x.Country }}
333 </li>
334</ul>
335
336</div>
337
338<script>
339var app = angular.module('myApp', []);
340app.controller('customersCtrl', function($scope, $http) {
341 $http.get("http://www.w3schools.com/angular/customers.php")
342 .success(function(response) {$scope.names = response.records;});
343});
344</script>
345
346Application explained:
347
348// The AngularJS application is defined by ng-app. The application runs inside a <div>.
349// The ng-controller directive names the controller object.
350// The customersCtrl function is a standard JavaScript object constructor.
351// AngularJS will invoke customersCtrl with a $scope and $http object.
352// $scope is the application object (the owner of application variables and functions).
353// $http is an XMLHttpRequest object for requesting external data.
354// $http.get() reads JSON data from http://www.w3schools.com/angular/customers.php.
355// If success, the controller creates a property (names) in the scope, with JSON data from the server.
356
357
358// Requests for data from a different server (than the requesting page), are called cross-site HTTP requests.
359// Cross-site requests are common on the web. Many pages load CSS, images, and scripts from different servers.
360// In modern browsers, cross-site HTTP requests from scripts are restricted to same site for security reasons.
361// The following line, in our PHP examples, has been added to allow cross-site access.
362header("Access-Control-Allow-Origin: *");
363
364
365///////////////////////////////////
366// AngularJS Tables
367
368// Displaying tables with angular is very simple:
369<div ng-app="myApp" ng-controller="customersCtrl">
370
371<table>
372 <tr ng-repeat="x in names">
373 <td>{{ x.Name }}</td>
374 <td>{{ x.Country }}</td>
375 </tr>
376</table>
377
378</div>
379
380<script>
381var app = angular.module('myApp', []);
382app.controller('customersCtrl', function($scope, $http) {
383 $http.get("http://www.w3schools.com/angular/customers.php")
384 .success(function (response) {$scope.names = response.records;});
385});
386</script>
387
388// To sort the table, add an orderBy filter:
389<table>
390 <tr ng-repeat="x in names | orderBy : 'Country'">
391 <td>{{ x.Name }}</td>
392 <td>{{ x.Country }}</td>
393 </tr>
394</table>
395
396// To display the table index, add a <td> with $index:
397<table>
398 <tr ng-repeat="x in names">
399 <td>{{ $index + 1 }}</td>
400 <td>{{ x.Name }}</td>
401 <td>{{ x.Country }}</td>
402 </tr>
403</table>
404
405// Using $even and $odd
406<table>
407 <tr ng-repeat="x in names">
408 <td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Name }}</td>
409 <td ng-if="$even">{{ x.Name }}</td>
410 <td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Country }}</td>
411 <td ng-if="$even">{{ x.Country }}</td>
412 </tr>
413</table>
414
415///////////////////////////////////
416// AngularJS HTML DOM
417
418//AngularJS has directives for binding application data to the attributes of HTML DOM elements.
419
420// The ng-disabled directive binds AngularJS application data to the disabled attribute of HTML elements.
421
422<div ng-app="" ng-init="mySwitch=true">
423
424<p>
425<button ng-disabled="mySwitch">Click Me!</button>
426</p>
427
428<p>
429<input type="checkbox" ng-model="mySwitch">Button
430</p>
431
432</div>
433
434//Application explained:
435
436// The ng-disabled directive binds the application data mySwitch to the HTML button's disabled attribute.
437// The ng-model directive binds the value of the HTML checkbox element to the value of mySwitch.
438// If the value of mySwitch evaluates to true, the button will be disabled:
439<p>
440<button disabled>Click Me!</button>
441</p>
442
443// If the value of mySwitch evaluates to false, the button will not be disabled:
444<p>
445 <button>Click Me!</button>
446</p>
447
448// The ng-show directive shows or hides an HTML element.
449
450<div ng-app="">
451
452<p ng-show="true">I am visible.</p>
453
454<p ng-show="false">I am not visible.</p>
455
456</div>
457
458// The ng-show directive shows (or hides) an HTML element based on the value of ng-show.
459// You can use any expression that evaluates to true or false:
460<div ng-app="">
461<p ng-show="hour > 12">I am visible.</p>
462</div>
463
464///////////////////////////////////
465// AngularJS Events
466
467// AngularJS has its own HTML events directives.
468
469// The ng-click directive defines an AngularJS click event.
470<div ng-app="myApp" ng-controller="myCtrl">
471
472<button ng-click="count = count + 1">Click me!</button>
473
474<p>{{ count }}</p>
475
476</div>
477<script>
478var app = angular.module('myApp', []);
479app.controller('myCtrl', function($scope) {
480 $scope.count = 0;
481});
482</script>
483
484// The ng-hide directive can be used to set the visibility of a part of an application.
485// The value ng-hide="true" makes an HTML element invisible.
486// The value ng-hide="false" makes the element visible.
487<div ng-app="myApp" ng-controller="personCtrl">
488
489<button ng-click="toggle()">Toggle</button>
490
491<p ng-hide="myVar">
492First Name: <input type="text" ng-model="firstName"><br>
493Last Name: <input type="text" ng-model="lastName"><br>
494<br>
495Full Name: {{firstName + " " + lastName}}
496</p>
497
498</div>
499
500<script>
501var app = angular.module('myApp', []);
502app.controller('personCtrl', function($scope) {
503 $scope.firstName = "John",
504 $scope.lastName = "Doe"
505 $scope.myVar = false;
506 $scope.toggle = function() {
507 $scope.myVar = !$scope.myVar;
508 };
509});
510</script>
511
512//Application explained:
513
514// The first part of the personController is the same as in the chapter about controllers.
515// The application has a default property (a variable): $scope.myVar = false;
516// The ng-hide directive sets the visibility, of a <p> element with two input fields,
517// according to the value (true or false) of myVar.
518// The function toggle() toggles myVar between true and false.
519// The value ng-hide="true" makes the element invisible.
520
521
522// The ng-show directive can also be used to set the visibility of a part of an application.
523// The value ng-show="false" makes an HTML element invisible.
524// The value ng-show="true" makes the element visible.
525// Here is the same example as above, using ng-show instead of ng-hide:
526<div ng-app="myApp" ng-controller="personCtrl">
527
528<button ng-click="toggle()">Toggle</button>
529
530<p ng-show="myVar">
531First Name: <input type="text" ng-model="firstName"><br>
532Last Name: <input type="text" ng-model="lastName"><br>
533<br>
534Full Name: {{firstName + " " + lastName}}
535</p>
536
537</div>
538
539<script>
540var app = angular.module('myApp', []);
541app.controller('personCtrl', function($scope) {
542 $scope.firstName = "John",
543 $scope.lastName = "Doe"
544 $scope.myVar = true;
545 $scope.toggle = function() {
546 $scope.myVar = !$scope.myVar;
547 }
548});
549</script>
550
551///////////////////////////////////
552// AngularJS Modules
553
554// An AngularJS module defines an application.
555// The module is a container for the different parts of an application.
556// The module is a container for the application controllers.
557// Controllers always belong to a module.
558
559// This application ("myApp") has one controller ("myCtrl"):
560
561<!DOCTYPE html>
562<html>
563<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
564<body>
565
566<div ng-app="myApp" ng-controller="myCtrl">
567{{ firstName + " " + lastName }}
568</div>
569
570<script>
571var app = angular.module("myApp", []);
572app.controller("myCtrl", function($scope) {
573 $scope.firstName = "John";
574 $scope.lastName = "Doe";
575});
576</script>
577
578</body>
579</html>
580
581// It is common in AngularJS applications to put the module and the controllers in JavaScript files.
582// In this example, "myApp.js" contains an application module definition, while "myCtrl.js" contains the controller:
583
584<!DOCTYPE html>
585<html>
586<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
587<body>
588
589<div ng-app="myApp" ng-controller="myCtrl">
590{{ firstName + " " + lastName }}
591</div>
592
593<script src="myApp.js"></script>
594<script src="myCtrl.js"></script>
595
596</body>
597</html>
598
599//myApp.js
600var app = angular.module("myApp", []);
601
602// The [] parameter in the module definition can be used to define dependent modules.
603
604// myCtrl.js
605app.controller("myCtrl", function($scope) {
606 $scope.firstName = "John";
607 $scope.lastName= "Doe";
608});
609
610// Global functions should be avoided in JavaScript. They can easily be overwritten
611// or destroyed by other scripts.
612
613// AngularJS modules reduces this problem, by keeping all functions local to the module.
614
615// While it is common in HTML applications to place scripts at the end of the
616// <body> element, it is recommended that you load the AngularJS library either
617// in the <head> or at the start of the <body>.
618
619// This is because calls to angular.module can only be compiled after the library has been loaded.
620
621<!DOCTYPE html>
622<html>
623<body>
624<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
625
626<div ng-app="myApp" ng-controller="myCtrl">
627{{ firstName + " " + lastName }}
628</div>
629
630<script>
631var app = angular.module("myApp", []);
632app.controller("myCtrl", function($scope) {
633 $scope.firstName = "John";
634 $scope.lastName = "Doe";
635});
636</script>
637
638</body>
639</html>
640
641
642///////////////////////////////////
643// AngularJS Applications
644
645// AngularJS modules define AngularJS applications.
646// AngularJS controllers control AngularJS applications.
647// The ng-app directive defines the application, the ng-controller directive defines the controller.
648<div ng-app="myApp" ng-controller="myCtrl">
649 First Name: <input type="text" ng-model="firstName"><br>
650 Last Name: <input type="text" ng-model="lastName"><br>
651 <br>
652 Full Name: {{firstName + " " + lastName}}
653</div>
654<script>
655 var app = angular.module('myApp', []);
656 app.controller('myCtrl', function($scope) {
657 $scope.firstName= "John";
658 $scope.lastName= "Doe";
659 });
660</script>
661
662// AngularJS modules define applications:
663var app = angular.module('myApp', []);
664
665// AngularJS controllers control applications:
666app.controller('myCtrl', function($scope) {
667 $scope.firstName= "John";
668 $scope.lastName= "Doe";
669});
Source & References ¶
Examples
References