Friday, February 21, 2014

Some notes on Angular.js

I have almost finished (read: abandoned) a project using Angular.js and here are some notes of little things that I would like to keep here so that I know where to find them next time.

This code snippet changes CSS class depending on the variable state:

ng-class="{CSSClassName: scopeVariable1 == scopeVariable2}"

The following regular expression finds the use of all scope variables that does not start with the letter "s":

\$scope\.[^s]+

Let's say there is a keyboard event, and the code needs to know what key was pressed. The following statement will provide the keycode to the function:

... ng-keypress="yourEventName($event.keyCode, otherArgsIfAny)" ...

Also, gotta remember that in JavaScript, when a variable's value is 'null', it means that there is such variable, but it has no value; when value is 'undefined' it means that there is no such variable.

In JavaScript, only the getMonth() function is zero-based (so December is month number 11), all other methods to get elements of a date are 1-based. To get year, use the getFullYear() function.

A new Date can be instantiated from milliseconds. For example:

var today = new Date(); //gets the date and time at the moment
var milliSec = Date.now(); //gets the number of milliseconds since epoch
//to reconstruct the date from millisec, just do this:
var someDate = new Date(millisec);

ng-show/ng-hide directives are pretty awesome to show/hide content:

...ng-show="oneVariable == anotherVariable"...

Or a function can be plugged in or a field or a string (if it is empty, then it would return false, otherwise -- true) or whatever else returns a boolean after evaluation.

Ordering a collection using Angular.js seems to be tricky. First of all, it only sorts arrays as of now. I had an array of object literals like so:

Let's say itemCollection has 3 items. $index is a 0-based variable, so for the first two items ($index is 0 and 1 and both times is less than three, so the span with a comma will be shown and the span with a period will be hidden. Then, on the last item $index equals to 2, which is >= to the (itemCollection.length-1), so the span with a comma will be hidden and the span with a dot will show up.