Javascript
Concepts
Contd…
TUTORIAL 5
Arrays
An array is a compound data type that stores
numbered pieces of data
Each numbered datum is called an element of
the array and the number assigned to it is called
an index.
The elements of an array may be of any type. A
single array can even store elements of different
type.
Creating an Array
There are several different ways to create an
array in JavaScript
Using the Array() constructor:
- var a = new Array(1, 2, 3, 4,
5);
- var b = new Array(10);
Using array literals:
- var c = [1, 2, 3, 4, 5];
Accessing Array Elements
Array elements are accessed using the [ ]
operator
Example:
var colors = [“red”, “green”, “blue”];
colors[0] => red
colors[1] => green
Adding Elements
To add a new element to an array, simply assign a
value to it
Example:
var a = new Array(10);
a[50] = 17;
Array Length
All arrays created in JavaScript have a special
length property that specifies how many elements
the array contains
Example:
var colors = [“red”, “green”, “blue”];
colors.length => 3
Primitive Data Types versus
Composite Data Types
Variables for primitive data types hold the actual
value of the data
Variables for composite types hold only
references to the values of the composite type
Variable Names
JavaScript is case sensitive
Variable names cannot contain spaces,
punctuation, or start with a digit
Variable names cannot be reserved words
Statements
A statement is a section Examples:
of JavaScript that can
Last_name = “Dunn”;
be evaluated by a Web
browser x = 10 ;
A script is simply a y = x*x ;
collection of statements
Programming Tips
It is a good idea to end Recommended:
each program
statement with a semi- a = 3;
colon; Although this is
b = 4;
not necessary, it will
prevent coding errors Acceptable:
a = 3; b = 4;
Wrong:
a =
3;
Aggregate Assignments
Aggregate assignments provide a shortcut by
combining the assignment operator with some
other operation
The += operator performs addition and
assignment
The expression x = x + 7 is equivalent to the
expression x += 7
Increment and
Decrement
Both the x = 10; x = 10;
increment (++) y = ++ x; z = x
and decrement ++;
(- -) operator
come in two
forms: prefix ⇒ y = 11
and postfix ⇒ z = 10
These two forms ⇒ x = 11 in both
yield different cases
results
Control Structures
There are three basic types of control structures in
JavaScript: the if statement, the while loop, and
the for loop
Each control structure manipulates a block of
JavaScript expressions beginning with { and
ending with }
The If Statement
The if statement If ( x = = 10)
allows JavaScript { y = x*x;
programmers to
a make decision }
Use an if else
statement { x = 0;
whenever you }
come to a “fork”
in the program
Repeat Loops
A repeat loop is a group of statements that is
repeated until a specified condition is met
Repeat loops are very powerful programming
tools; They allow for more efficient program
design and are ideally suited for working with
arrays
The While Loop
The while loop count = 0;
is used to while (count <= 10) {
execute a document.write(count
block of code );
while a certain
condition is true count++;
}
The For Loop
The for loop is used when there is a need to have
a counter of some kind
The counter is initialized before the loop starts,
tested after each iteration to see if it is below a
target value, and finally updated at the end of
the loop
Example: For Loop
// Print the i=1 initializes the
numbers 1 counter
through 10
i<=10 is the target
for (i=1; i<= 10; i++) value
document.write(i
);
i++ updates the
counter at
the end
of the loop
Example: For Loop
<SCRIPT <SCRIPT
LANGUAGE= LANGUAGE=
"JavaScript"> "JavaScript">
document.write("1");
document.write("2");
for (i=1; i<=5; i++)
document.write("3");
document.write(i);
document.write("4");
document.write("5");
</SCRIPT>
Functions
Functions are a collection of JavaScript statement
that performs a specified task
Functions are used whenever it is necessary to
repeat an operation
Functions
Functions have inputs and outputs
The inputs are passed into the function and are
known as arguments or parameters
Think of a function as a “black box” which
performs an operation
Defining Functions
The most common way to define a function is
with the function statement.
The function statement consists of the function
keyword followed by the name of the function, a
comma-separated list of parameter names in
parentheses, and the statements which contain
the body of the function enclosed in curly braces
Example: Function
function Name of Function:
square(x) square
{return x*x;}
Input/Argument: x
z = 3;
sqr_z = square(z); Output: x*x
Example: Function
function sum_of_squares(num1,num2)
{return (num1*num1) + (num2*num2);}
function sum_of_squares(num1,num2)
{return (square(num1) + square(num2));}
Why AngularJS
MVC Javascript Framework by Google for Rich Web Application
Development
“Other frameworks deal with HTML’s shortcomings by either abstracting
away HTML, CSS, and/or JavaScript or by providing an imperative way for
manipulating the DOM. Neither of these address the root problem that HTML
was not designed for dynamic views”.
Structure, Quality and Organization
Lightweight ( < 36KB compressed and minified)
Free
Separation of concern
Modularity
Extensibility & Maintainability
Reusable Components
jQuery
Allows for DOM Manipulation
Does not provide structure to your code
Does not allow for two way binding
Other Javascript MV*
Frameworks
BackboneJS
EmberJS
Features of AngularJS
Two-way Data Binding – Model as single source of
truth
Directives – Extend HTML
MVC
Dependency Injection
Testing
Deep Linking (Map URL to route Definition)
Server-Side Communication
Data Binding
<html ng-app>
<head>
<script src='angular.js'></script>
</head>
<body>
<input ng-model='user.name'>
<div ng-show='user.name'>Hi {{user.name}}</div>
</body>
</html>
MVC
Model View Controller.
Model
(Data) View (UI)
Notifies
Notifies
Changes
Controller
(Logic)
MVC
Model JS Objects
View DOM
Controller JS Classes
MVC
<html ng-app>
<head>
<script src='angular.js'></script>
<script src='controllers.js'></script>
</head>
<body ng-controller='UserController'>
<div>Hi {{user.name}}</div>
</body>
</html>
function XXXX($scope) {
$scope.user = { name:'Larry' };
}
Expressions
Expressions allow you to execute some
computation in order to return a desired value.
{{ 1 + 1 }}
{{ 946757880 | date }}
{{ user.name }}
you shouldn’t use expressions to implement any
higher-level logic.
Directives
Directives are markers (such as attributes, tags, and
class names) that tell AngularJS to attach a given
behaviour to a DOM element (or transform it,
replace it, etc.)
Some angular directives
The ng-app - Bootstrapping your app and defining
its scope.
The ng-controller - defines which controller will be in
charge of your view.
The ng-repeat - Allows for looping through
collections
Directives as Components
<rating max='5' model='stars.average'>
<tabs>
<tab title='Active tab' view='...'>
<tab title='Inactive tab' view='...'>
</tabs>
<tooltip content='messages.tip1'>
Adding Controllers
angular.module('F1FeederApp.controllers', []).
The $scope variable –
controller('driversController', function($scope) {
Link your controllers and
$scope.driversList = [ view
{
Driver: {
givenName: 'Sebastian',
familyName: 'Vettel'
},
points: 322,
nationality: "German",
Constructors: [
{name: "Red Bull"}
},
Driver: {
givenName: 'Fernando',
App.js
angular.module('F1FeederApp', [
'F1FeederApp.controllers'
]);
Initializes our app and register the modules on
which it depends
Index.html
<body ng-app="F1FeederApp" ng-controller="driversController">
<table>
<thead>
<tr><th colspan="4">Drivers Championship Standings</th></tr>
</thead>
<tbody>
<tr ng-repeat="driver in driversList">
<td>{{$index + 1}}</td>
<td>
<img src="img/flags/{{driver.Driver.nationality}}.png" />
{{driver.Driver.givenName}} {{driver.Driver.familyName}}
</td>
<td>{{driver.Constructors[0].name}}</td>
<td>{{driver.points}}</td>
</tr>
</tbody>
Loading data from the
server(services.js)
angular.module('F1FeederApp.services', []). $http - a layer on top
of XMLHttpRequest or JSONP
factory('ergastAPIservice', function($http) {
$resource - provides a higher level of
var ergastAPI = {}; abstraction
ergastAPI.getDrivers = function() { Dependency Injection
return $http({
method: 'JSONP',
url:
'http://ergast.com/api/f1/2013/driverStandin
gs.json?callback=JSON_CALLBACK'
});
}
return ergastAPI;
}); we create a new module
(F1FeederApp.services) and register a
service within that module
(ergastAPIservice).
Modified controller.js
angular.module('F1FeederApp.controllers', []).
controller('driversController', function($scope,
ergastAPIservice) {
$scope.nameFilter = null;
$scope.driversList = [];
ergastAPIservice.getDrivers().success(function (response) {
//Dig into the responde to get the relevant data
$scope.driversList =
response.MRData.StandingsTable.StandingsLists[0].DriverSt
andings;
});
});
Routes
$routeProvider – used for dealing with routes
Modified app.js
angular.module('F1FeederApp', [
'F1FeederApp.services',
'F1FeederApp.controllers',
'ngRoute'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when("/drivers", {templateUrl: "partials/drivers.html", controller: "driversController"}).
when("/drivers/:id", {templateUrl: "partials/driver.html", controller: "driverController"}).
otherwise({redirectTo: '/drivers'});
}]);
Partial views
<!DOCTYPE html>
<html>
<head>
<title>F-1 Feeder</title>
</head>
<body ng-app="F1FeederApp">
<ng-view></ng-view>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
</body>
</html>
Advanced AngularJS
Concept
Dependency Injection
Modularity
Digesting
Scope
Handling SEO
End to End Testing
Promises
Localization
Filters