Getting Started with Angular JS

I’ve been looking at angular JS as a beginner, and so I’ve been looking at what things like controllers and directives are. Here are my notes so far:

Learning Angular JS

Code School Notes

Instead of re-requesting the entire web-page, re-downloading all html ect, Angular JS only requests the information needed, sent in the form of JSON data.

It is a modern API-Driven front end application.

Include the angular library with <script type=“text/javascript” src=“angular.min.js”></script>

Directives

Angular JS adds behaviour to HTML through Directives, which is a marker on a HTML tag which tells angular to run javascript/html.

e.g: <body ng-controller=“StoreController”>

Runs the function “StoreController”, although this example code would normally not be used.

Modules

Modules are pieces of the angular application, it makes the code more maintainable, testable and readable. Also easier to check dependancies (code that relies on other code to run).

e.g: var app = angular.module(‘store’,[]);

var = variable
app = name of the variable
angular = references the angular library
module = refers to module in the library, because its a module
store = name of the module (can be anything)
[ ] = any dependancies go in here, add this because its an array

The code above would be contained in the Javascript file, and referenced via a directive in HTML:

i.e: <html ng-app=“store”>

ng-app is a directive that can only be used once in a page, and allows everything inside the element to be run through angular, allowing for expressions.

Expressions

e.g.<p> I am {{4 + 6}}</p>
This would come out as “I am 10” if the element is run through angular.

Controllers

Helps us get data onto the page:

var gem = {
name: ‘Dodechahedron
price: 2.95
description: ‘. . . .’
}

This variable will be in the javascript page, however it needs to be placed in the HTML, you use functions to do this in the app.js file:

(function(){
var app = angular.module(‘store’,[ ]);
app.controller(‘StoreController, function(){ //StoreController is controller name, can be anything.
this.product = gem; //product is a property of
the controller, = gem references the variable
below
});
var gem = {
name: ‘Dodechahedron
price: 2.95
description: ‘. . . .’
}
})();

in the HTML to add the controller write:

<div ng-controller=“StoreController as store”> //StoreController is name of controller, as is a keyword, store is an alias for the controller.
<h1> {{store.product.name}}</h1>
<h2>$store.product.price}}</h2>
<p>{{store.product.description}} </p> //These three
are values of the store controller.
</div>

Responsive Design

I’ve looked into the possibility of needing an app for Speakers Corner and although the web-browser version would be limited on how it could communicate with the device, there is little need for more than location. Although notifications for replies would work well, I think email notifications would work well enough. There could be a possibility for an app in the future though.

So I’ve looked at the responsive design for HTML, resizing the window will be quite simple, with this simple code. Beyond that, I’ll need to have the sections of the site to re-order themselves depending on room.

HTML:

<html>
<body>
    <div id="wrapper"></div>
</body>
</html>

CSS:

html, body, {
    position:fixed;
    top:0;
    bottom:0;
    left:0;
    right:0;
}

Learning Javascript

Over the past week I’ve been working through a Lynda tutorial on Javascript basics, I think I’ve got a good hold on the language and will be starting work on the site while I finish up this course and Jquery. Here are the notes:

Javascript Lynda Notes

Programming language that is intentionally limited (cannot save/load local files), so often considered not a scripting language.

It was designed to manipulate web pages, running client-side. Unlike languages like PHP.

Does not need to be compiled, and is CASE SENSITIVE.

Javascript can be disabled client side, so make sure your site still works without it.

Adding Javascript

<script>script here</script>

e.g. <script> alert(“hello world!”);</script>

Software for Java

Recommended: Get a version of every browser

Firefox has great debugging tools, also install the Firebug extension to allow direct experimentation in the browser.

Starting

End every statement with a semi-colon, does’t need to be on different lines but its good practice.

Put Javascript at the end of a html file so that the javascript is loaded after the HTML is.

Java doesn’t care about spaces.

Comments

//everything after a double forward slash on a line is a comment, can be put after code as well.

/* for multiple lines a fowardslash star can
be used, ending with the reverse. */

Where to write Javascript

The <script> element is good for a few unique pages (i.e. inline javascript).

Using a separate .js file is best for larger amounts of code.
To link an external script use:
<script src=“my script.js”></script>
Src = source

Legacy browsers had type=“text/javascript”> after the quotation marks but that isn’t necessary with HTML 5.

Usually, put the script tag at the end of the HTML page, just before the </body> tag.

Variables

var points to a variable, the name of the variable comes after var. The name cannot include spaces and cannot start with a number (but can include numbers).

var nameofvariable;

This creates the variable, but does not have a value (i.e. an undefined variable.

Adding values can be done like this

nameofvariable = 1009;
or: var nameofvariable = 1009; to add the variable and value.

On the 2nd example, var isn’t necessary, but it is good practice to always add as it can break your code in some situations if you don’t.

Variable names are case sensitive.

To create multiple variables write:

var year, month, day; and to add multiple values as well write:
var year = 2017, month = 2, day = 6;

Variables are generic, and don’t have different types like other languages.
Can use double and single quotes, but not interchangeably (stick to one type).

Conditional Code

if (condition) {
code to run if condition is true.
}

To check equality use two =
(Triple equals sign works)

i.e.:
if ( c == 99 ) {
code
}

To check for not equal numbers type !=

To make it execute code of the statement is false use:

if ( c != 100 ) {
alert (“not 100”);
} else {
alert (“is 100):
}

Operators

Arithmetic operators
+-*/

= : Assigns value to a number (only 1 equals)

Adding to a variable:

Score = score + 10

Adds 10 to the value of score and reassigns that number to score. Shorthand you can write:

score += 10
score -= 10
score *= 10
score /= 10

It works on BIDMAS

= Assign
== Equality
=== Strict equality
!== not strictly equal to
!= not equal to
>= greater than or equal to
> greater than

If a value is stored as a value, and another is stored as a string (with “quotations”), even if its the same number the triple equal sign will say they aren’t equal, whereas the double will.
(ie. triple equal sign checks the syntax in the code)

Most of the time

And/Or Operators

if (a === b && c === d {….
asks if a=b AND c = d

if ((a === b) || (c === d) {….
Asks if A=B OR C=D

Modulus Operators
% asks to divide but take the remainder
IE.
var year = 2003;
var remainder = year % 4;

This divides 2003 by 4 and checks the remainder instead of the result (4*500= 2000 with a remainder of 3)

Incremental addition Operators

If you just want to add 1 to a variable use:

a++;
++a
a = a + 1;
a += 1;

Minus, use:
a—:
—a:

Can be used before or after the variable (a), however, it will still execute code in order. i.e..
alert(a++); displays value of A but doesn’t add 1 on until after it is shown.

Ternary Operators

condition ? true : false

var playerOne = 500;
var playerTwo = 600;

To check which one is higher and return the value of that one use:

var highScore = (playerOne > playerTwo) ? playerOne : playerTwo

i.e. condition = playerOne > playerTwo
if true (true first) return playerOne value
if false (after colon) return the value of playerTwo

Firebug feature

Replace Alert with console.log to stop constant alerts coming up. It’ll only work in debuggers with that code added, it isn’t official javascript.

Working with loops (iteration)

var a = 1;
while ( a < 10 ) {
console.log(a);
a++
}

Create variable A with a value of 1, check the value and if it is less than 10 log the number in the console then add 1.
Without the a++ it would be an infinite loop.

do {
console.log(a);
a++
} while ( a < 10);

This is less common, the difference is this code will always run once then check the condition.

for ( var i = 1 ‘ i < 10 ; i++ ) {
//code
}

Just a shorthand way to do it, creates variable i with value 1, checks if its less than 10, adds 1 to it then runs the code if its less than 10.

Break

for (var i = 1 : i < 5000 ; i++) {
//code
if (i==101) {{
break:
}
//code
}

Loops the code, adding 1 to i until i = 101, then running ‘break;’ which skips out of the conditional statement.

Continue

Replace break; with continue; to instead of breaking away from the condition, finish this loop and return to the start of the statement.

Adding Functions

function functionName () {
//function code
}

Functions do not automatically run. To run it, put:

functionName();

Anywhere in the code. You should define your functions before you call them, but you don’t have to.

To create functions that expect to be passed information:

function functionName ( x,y ) {
var myVar = x + Y
}

Now when calling the function, typing:

functionName ( 4,8);

will use 4 as x and 8 as y, adding them together.
To return a value, use:

return myVar;

It will be ignored if you don’t use it, such as with:

var myResult = functionName ( 4,8 );

This would run the function, then any value returned would be added to myResult value.

Creating a variable inside a function does not create the variable outside the function.

Creating Arrays

Created much like variables, but arrays have more than 1 value.

var arrayName = [];
The [] indicates its an array, you can add multiple values with:

arrayName[0] = 50;
arrayName[1] = 60;
arrayName[2] = 65;
arrayName[3] = mouse;

To use the values:
console.log(arrayName[3]); prints ‘mouse’ in the console

Shorthand:
var arrayName = [ 50,60,65,mouse];

This adds variables in order, starting from 0, adding as many as you’d need. Other ways that work creating arrays are:

var arrayName = new Array ();
var arrayName = Array ();

The Array is an ‘object’ so it can be used these ways.
To add a size to the array, use:

var arrayName = Array (5);

Creates an array with 5 slots, but this isn’t needed as all arrays are dynamic.

Array Properties

console.log(arrayName.length);
Shows the amount of slots used in an array.

Array Methods

A method is a function that belongs to an object, as arrays are objects these can be used.

someObject.someMethod(): to call a method. i.e:

var arrayName = [50,60,65,mouse];
var reversedArray = arrayName.reverse();

This creates another array with the values reversed.
others include:
.join();
.sort();

console.log(reversedArray.join());
This will print out ‘mouse,65,60,50’ to the console log.

Working with numbers

All Javascript numbers are 64-bit floating point numbers.
Adding numbers as variables with quotations adds it as a string. Adding strings together won’t add the numbers together, but combine the strings. (‘5’ + ‘5’ = ’55’, 5 + 5 = 10)

To check if a string is a number, use:
var myNumber = Number (variableName);

if (!isNaN(myNumber) ) {
console.log(“it is a number”);
}

This creates a variable called myNumber, if variableName is not a number (checked with = Number) it will return with NaN, which is added to the myNumber variable.

The 2nd half checks if myNumber does not (with !) = NaN, and if it isn’t, it should be a number, so the console prints “it is a number”)

Using the Math Object

var x = 200.6;
var y = Math.round(x);

This adds variable y which is a rounded version of x
Others include;

Math.max which picks the largest of a series of numbers
Math.max which does the opposite
Math.PI
Math.random
Math.sqrt
Math.log

Working With Strings

Using quotes inside of quotes
Use quotes around a string, can be ‘ or “ but not both, if using quotations in the string you can’t use the one you put around the string.
Unless you use \ e.g:
var phrase = “He said \ that’s fine,\” and left.”;

String Properties
var phrase = “phase goes here”;
console.log(phrase.length); To check the length of a string and print it.
phrase.toUpperCase(); changes all characters to uppercase.
phrase.toLowerCase();
phrase.split(“ “) creates an array from the string, using spaces to split the string up as a space is in the quotations, this can be changed to anything.
var position phrase.indexOf(“goes”) checks for how far in the string a phrase is, gives the amount of characters that appear before the phrase. Returns -1 if the string is not found.
phrase.lastindexof() finds the last phrase in the string.
var segment = phrase.slice(6,10); takes from character 6 to 10 and outputs it to variable segment. (i.e: goes)
.substring () works the same as slice
.substr() is similar but the 2nd number is the length of the segment rather than the end character.

if ( str1.toLowerCase() == str2.toLowerCase() ) {
console.log(“Yes, equal”);
}
Good for comparing strings without being case sensitive.
Remember using < or > that capitals are worth less than lower case.

Working with dates
var today = new Date (); prints current date and time.
var y2k = new Date (2000,0,1); prints year 2000, current month, then day 1(goes on to minutes, then seconds);

today.getMonth();  shows month, 0-11
today.getFullYear(); shows year
today.getDate(); shows date, 1 – 31
today.getDay(); shows day of the week, 0 – 6
today.getHours(); shows hour of day 0 – 23
today.getTime(); shows time in milliseconds since 1/1/1970
today.setMonth(5); sets the month to 5
today.setFullYear(2012) sets the year to 2012
today.setDay (0); sets the day to 0

if (date.getTime() == date2.getTime() ) {
to check if dates are equal, as not using getTime always returns as false.

Objects in Javascript
An object is a container, gathering together variables and functions.

var playerName = “Fred”;
var playerScore = 10000:
var playerRank = 1;
This creates separate variables, but can be joined together with an object:
var player = new Object();
player.Name = “Fred”;
player.Score = 10000:
player.Rank = 1;
This creates an object called player, and adds properties called Name, Score and Rank

var player1 = { name:”Fred”, score: 10000, rank: 1 };
var player2 = { name:”John”, score: 5000, rank: 3 };
is the shorthand way of creating it.

console.log(player1.name); prints ‘Fred’

function playerDetails(){
//code
}
Creates a function called playerDetails

player1.logDetails = playerDetails;
player1.logDetails = playerDetails;
This assigns a method to the object, which is the function playerDetails.

function playerDetails(){
console.log(this.name + “has a rank of “ +
this.rank “ and a score of “ + this.score);
}

Adding this to a method will pull the object the method is assigned to, so if you use:
player1.logDetails(); it will print the name, score and rank of player 1 after logDetails was assigned to playerDetails the () after logDetails tells it you want to call that variable/property.

What is the DOM – Document object model

The document objects model is terminology to help javascript work with HTML/CSS. It is structured using nodes, and where they are nested.

<ul id=“optionList”>
<li>first</li>
<li>second</li>
<li>third</li>
</ul>
The whole piece of code is considered an element node.
As it has been tagged it is also an attribute node.
The <li> inside the list is considered another element node
The text inside the <li> elements is a text node.

Element nodes do not contain the text inside the element.

How to get an element node

var myElement = document.getElementById(“abc”)
creates an element called myElement and adds the element with the Id of ‘abc’ to the variable.

document.getElementsByTagName(“a”)
Will get all elements that are anchor <a> elements, creates an array with each anchor included. If it can’t find the elements it will create the array but not add anything.
var mainTitle = document.getElementById(“mainTitile”);
mainTitle.nodeType Checks the type the node is, outputting 1,2 or 3 for elements, attributes and text.
mainTitle.innerHTML shows the html written inside the element
mainTitle.childNodes shows the amount of child nodes are inside the element.

var newList = oldList.getElementsByTagName(“a”)
Creates a new array of all anchor elements inside variable oldList, which can be created like any other variable.

Changing DOM Elements

myElement.getAttribute(“align”); will fetch the align attribute of myElement, align can be replaced with any attribute.
myElement.getAttribute(“align, right”); sets the alignment of myElement to the right.
If the attribute doesn’t exist it will be created.

Creating DOM Content
1. Create the element
2. Add it to the document

var myNewElement = document.createElement(“li”);
will create the <li> tag
myElement.appendChild(myNewElement);
will find the myElement variable and add the <li> element to it. (if var myElement = document.getElementById(“abc”) is written earlier it will add a <li> nested inside the element tagged ‘abc’)
var myNewElement = innerHTML(“new item text”);
is one way to add text to myNewElement.

Creating Text Nodes
var myText = document.createTextNode(“text”);
myNewElement.appendChild(myText);
Is a better, more exact way to do it.