webpackJsonp([81498132038367],{366:function(e,t){e.exports={data:{markdownRemark:{html:'

\n \n \n \n \n \n

\n

Data Types

\n

JavaScript is a loosely typed language which means a variable\'s value defines its type. JavaScript has 7 data types grouped as follows:

\n

Primary / Primitive (Have no properties and are immutable)

\n\n

Composite / Reference (Are objects so have properties and are mutable)

\n\n

Special (Classed as primary / primitive but with no corresponding object constructor)

\n\n

Certain operations will cause the JavaScript interpreter to coerce a variable\'s type to allow it to complete the requested operation without causing an exception. For example adding a number or a boolean to a string will convert the former variable to a string too (and concatenate the two). Adding a boolean to a number will convert the boolean to a number before adding the values together.

\n

Also note that whilst the primitive types are not objects (unless instantiated with the new keyword, see below), they still have properties/methods available to them from their corresponding object constructor. This is because JavaScript temporarily creates an object wrapper whilst it accesses/performs the requested property/method. This object is immediately destroyed afterwards which explains why you can\'t access a property that you just added to a primitive, it\'s gone already!

\n

Built-In Objects

\n

Everything in JavaScript except primitive values are objects. Note that objects in JavaScript are addressed by reference which means assigning an object to the value of another variable does NOT make a copy of the object. It merely creates another pointer to the same object.

\n

String

\n

Instantiation

\n
\'string\', "string", String(thing), new String(thing)
\n

Properties

\n
length
\n

Methods (most common)

\n
charAt(index), indexOf(needle), match(regexp), replace(needle|regexp, newNeedle), search(needle|regexp), slice(start, exclusiveEnd), split(delimiter|regexp,limit), substr(start, inclusiveEnd), substring(start, exclusiveEnd), toLowerCase(), toUpperCase, trim(), valueOf()
\n

Number

\n

Instantiation

\n
new Number(value)
\n

Methods (most common)

\n
toFixed(decimals), toPrecision(length), toString(), valueOf()
\n

Boolean

\n

Instantiation

\n
new Boolean(value)
\n

Methods

\n
toString(), valueOf()
\n

Date

\n

Instantiation

\n
new Date(milliseconds|dateString|year, month, date[, hours[, minutes[, seconds[, milliseconds]]]])
\n

Methods

\n
get|set + UTC + Date|Day|FullYear|Hours|Milliseconds|Minutes|Month|Seconds|Time + (),
to + Date|GMT|ISO|LocaleDate|LocaleTime|Locale|Time|UTC + String(),
toJSON(), now(), parse(dateString), valueOf(),
UTC(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]])
\n

Math

\n

Instantiation

\n

Math objects don\'t need to be instantiated and so can just be used with the required property or method directly.

\n

Methods (most common)

\n
abs(x), ceil(x), floor(x), max(x, ...), min(x, ...), pow(base, exponent), random(), round(x), sqrt(x)
\n

RegExp

\n

Instantiation

\n
/pattern/modifiers, new RegExp(pattern, modifiers)
\n

Methods (most common)

\n
exec(string), test(string)
\n

Also note that the String object\'s match(), replace(), search() and split() methods all accept RegExp patterns as arguments. Learn more about JavaScript regular expressions.

\n

Array

\n

JavaScript arrays are classed as objects except with a numerical index (rather than names/strings). As objects, they can contain mixed collections of data types including objects, functions and other arrays.

\n

Instantiation

\n
[element0, ...], new Array(element0 , ...|arrayLength)
\n

Properties

\n
length (number of elements)
\n

Methods (most common)

\n
concat(array2, ...), indexOf(needle), isArray(object), join(separator), shift(), pop(), unshift(item1, ...), push(item1, ...), sort(), reverse(), slice(start, exclusiveEnd), splice(index, numToRemove, itemToAdd1, ...), valueOf()
\n

Object

\n

Objects contain name:value pairs. The names must be a string (they can be numbers or reserved words but must be enclosed in quotes). The values can be of any data type including arrays, functions (methods) and other objects.

\n

Instantiation

\n
{name: value, ...}, new Object(value)
\n

Properties

\n
Whatever you define
\n

Methods (most common)

\n
Whatever you define, hasOwnProperty(name), propertyIsEnumerable(name), toString(), valueOf()
\n

Function

\n

Functions can be created as a declared function or as a function expression and can be assigned to a variable or object property (as a method). Function expressions can be created without a name as an anonymous function expression. They can even invoke themselves (self-invoked/self-executing/immediately-invoked function expression) as in run automatically on script load. All functions, regardless of how they are created can receive arguments via parameters. When invoked (or called), functions execute the code/procedure contained within. Functions often return a computed value back to the caller of the function. This return value can also be another nested function as in the module pattern. Yes, functions can be nested too (see closures below).

\n

Declaration/Creation

\n
function functionName(param1, ...) { code }, new Function(param1, ..., code), var functionName = function (param1, ...) { code }, functionName: function (param1, ...) { code }, (function (param1, ...) { code })()
\n

Properties

\n
length (number of parameters expected), arguments (.length, [i])
\n

Invocation

\n
functionName(arg1, ...), objectName.functionName(arg1, ...), new functionName(arg1, ...), (function (arg1, ...) { code })()
\n

Closures

\n

Closures allow us to create and access more secure, private variables within functions. Perfect for function factories, they also make it possible to persist an outer function\'s declared variables and arguments from within the inner function to be returned by the factory.

\n
function makeMyCar( car ) {\n\tcount = 0;\n\treturn function( colour ) {\n\t\tcount++;\n\t\tconsole.log( "You are #" + count + " in the " + car + " queue. Your chosen colour is " + colour + ".");\n\t};\n}  \n  \nvar fiestaFactory = makeMyCar( "Fiesta" );\nfiestaFactory( "Goblin Green" ); // You are #1 in the Fiesta queue. Your chosen colour is Goblin Green.  \n  \nvar bentleyFactory = makeMyCar( "Bentley" );\nbentleyFactory( "Posh Purple" ); // You are #1 in the Bentley queue. Your chosen colour is Posh Purple.  \n  \nfiestaFactory( "Perky Pink" ); // You are #2 in the Fiesta queue. Your chosen colour is Perky Pink.\n
\n

Hoisting

\n

JavaScript will automatically hoist all variable and function declarations to the top of the current scope, regardless of where they were declared in the script. Note that initialisations of variables and functions expressions will not be hoisted.

\n
console.log( x ); // undefined (the variable definition of x has been hoisted but not initialised yet)\nvar x = 123;\nconsole.log( x ); // 123 (now the variable x has been initialised)\n
\n

Strict Mode

\n

If we want to enforce a stricter environment and provide more error/exception information, we can tell browsers to compile in strict mode by placing the following either at the top of the script (global setting for the whole script) or within a function (local setting).

\n
"use strict mode"\n
\n

Strict mode enforces a boatload of restrictions such as preventing the use of undeclared variables, duplication of object and function parameters and assigning values to non-writable object properties.

\n

JavaScript Reference

\n

Here are some handy places to find a detailed reference for JavaScript:

\n',frontmatter:{teaser:"A quick reference guide to JavaScript Data Types, Built-In Objects (Hint: Almost everything is an object!) and some additional tips.",date:"07 January 2015",path:"/blog/javascript-cheat-sheet",title:"JavaScript Cheat Sheet"}}},pathContext:{prev:{html:'

\n \n \n \n \n \n

\n

JavaScript Objects

\n

Javascript objects can be created using new Object() or by object literal notation (preferred) and whatever properties and methods (functions within an object) we wish added.

\n
car = new Object();  \n  \ncar.manufacturer = "Bugatti";\ncar.model = "Veyron";\n
\n
car = {\n    manufacturer: "Bugatti",\n    model: "Veyron"\n}\n
\n

Unlike JavaScript primitives like string or number, objects are addressed by reference. This means that assigning an existing object to another variable will not make a copy. The new object will just point to the same object that the original one does. Changing either of these objects will change both of them.

\n
anotherCar = car;  \n  \nanotherCar.manufacturer = "McLaren";\nanotherCar.model = "P1";  \n  \nconsole.log( anotherCar ); // Object {manufacturer: "McLaren", model: "P1"}\nconsole.log( car ); // Object {manufacturer: "McLaren", model: "P1"}\n
\n

We can use Object.create() to make new objects that inherit all properties and methods from an existing object. However we still have to replace/set all the values of the new object so no real advantage to this approach. We may as well just create new objects from scratch.

\n
anotherCar = Object.create( car );  \n  \nanotherCar.manufacturer = "McLaren";\nanotherCar.model = "P1";  \n  \nconsole.log( anotherCar ); // Object {manufacturer: "McLaren", model: "P1"}\nconsole.log( car ); // Object {manufacturer: "Bugatti", model: "Veyron"}\n
\n

So what if we want lots of different objects that are of the same type? What is the best approach to handling object creation?

\n

Object Constructor Functions

\n

All built-in objects (with the exception of Math) have their own constructors. When we use the new keyword, we are telling JavaScript to use the constructor of the following object ie. new Date(). Constructors may also receive arguments to be used within the construction process.

\n

A constructor function is similar to a class in other OO languages in that we can define properties to store our data, and methods to perform operations on this data. It is accepted convention in JavaScript to always capitalise the first character of a constructor function name to help differentiate it from regular functions.

\n
function Car( manufacturer, model, wheels ) {\n    this.manufacturer = manufacturer;\n    this.model = model;\n    this.wheels = wheels;\n    this.start = function() {\n        console.log( "Nice " + this.manufacturer + " " + this.model + ", let\'s roll!" );\n    };\n}\n
\n

Note the use of the this keyword. In the context of a constructor function (when called with the new keyword), this relates to the object being created. Also note that we are not returning anything either as the properties and methods are being defined directly on this object.

\n

We can now create/instantiate new objects with our constructor and pass in the values to be set.

\n
var modelS = new Car( "Tesla", "Model S", 4 );  \n  \nconsole.log( modelS ); // Car {manufacturer: "Tesla", model: "Model S", wheels: 4, start: function}\nmodelS.start(); // Nice Tesla Model S, let\'s roll!\n
\n

Objects have a constructor property which is automatically set with a reference to the constructor function used to create it. We can check this with the following methods:

\n
console.log( modelS.constructor == Car ); // true\nconsole.log( modelS instanceof Car ); // true\n
\n

However, a problem remains that new objects all have a copy of all the properties and methods, regardless of whether or not they will every need or use them. What if we could keep certain properties and methods in a central place so that all instances of an object could access them only when required?

\n

Object Prototypes

\n

Every object has a prototype property which, as it sounds, is a kind of template that an object\'s constructor uses when creating new instances of itself.

\n

Every built-in object (with the exception of Math which doesn’t have a constructor) has a prototype property with its own properties and methods defined within. Thus an instance of Array or Date for example inherits a multitude of methods from its constructor\'s prototype without carrying the weight of these within the instance itself. Objects created using new Object() or object literal notation directly inherit properties and methods from Object.prototype such as constructor, hasOwnProperty(), toString(), etc.

\n

We can define our own prototypes for our constructor functions and move any properties or methods that we wish to share over to the prototype. Let\'s rewrite our Car example:

\n
function Car( manufacturer, model, wheels ) {\n    this.manufacturer = manufacturer;\n    this.model = model;\n    this.wheels = wheels;\n}  \n  \nCar.prototype.start = function() {\n    console.log( "Nice " + this.manufacturer + " " + this.model + ", let\'s roll!" );\n};  \n  \nvar modelS = new Car( "Tesla", "Model S", 4 );  \n  \nmodelS.start(); // Nice Tesla Model S, let\'s roll!\n
\n

Note that we could have defined the prototype with object literal notation. This has the advantage of being able to define multiple properties and methods with less code. However, as this effectively replaces the whole property, we have to redefine the constructor property.

\n
Car.prototype = {\n    constructor: Car,\n    start: function() {\n        console.log( "Nice " + this.manufacturer + " " + this.model + ", let\'s roll!" );\n    }\n}\n
\n

Objects also have a prototype attribute or object (not to be confused with the prototype property above) which is automatically set and shows where an object descends from i.e. its parent. The attribute stores a reference to the constructor\'s prototype. So for example a new Object() would descend directly from Object.prototype, an object instantiated from new Date() would descend from Date.prototype, and in our Car example an object would descend from Car.prototype. We can use the following methods to check which prototype was used to create an object:

\n
console.log( Car.prototype.isPrototypeOf( modelS ) ); // true\nconsole.log( Object.getPrototypeOf( modelS ) === Car.prototype ); // true (IE9+)\n
\n

Inheritance and the Prototype Chain

\n

JavaScript objects can inherit from other objects, which can in turn inherit from other objects, and so on. If we create a new Date object for example, this would inherit from Date.prototype which in turn inherits from Object.prototype, creating a chain of inheritance. All objects, be they custom or built-in, ultimately inherit from Object.prototype.

\n

When a property is referred to, or a method is called, JavaScript will firstly check in the current object to see if that property or method is defined. If it isn\'t, the object\'s prototype attribute is looked up (following the prototype chain) and the object defined there is then checked. This chain lookup continues until a matching property or method is found.

\n

There are several different approaches/patterns used to implement inheritance for our own JavaScript objects, each with their own pros and cons. Let\'s look at two of the most popular patterns using our Car example again and add in a new parent object type Vehicle with its own properties and methods.

\n

Combination Inheritance

\n

We saw earlier that we can create an object via a constructor function, and we can also add properties and methods to the constructor\'s prototype that we wish to share with all child objects. We run into problems though if any of the constructor properties hold a composite value such as an array or an object. Primitive values such as string or number are fine because the value will likely be replaced by the instantiated object. Composites however are only references to an object. This means that any instantiated objects would inherit the reference to the same property object. Altering that property value, such as adding an item into an array, would change the referenced object and so change the value for all child objects. So what can be done?

\n

This pattern is so called because it combines constructor stealing with prototype chaining. It is an attempt to replicate in some ways a classical inheritance pattern found in many other Object Oriented languages. Basically, we use prototype chaining to inherit the properties and methods defined on the constructor\'s prototype and we inherit the instance properties (defined in the constructor itself) by stealing the whole constructor. In practice we achieve this by setting the Car prototype attribute to inherit from the Vehicle.prototype (ensure this is done before defining any prototype properties or methods on Car). Then we tell the Car constructor to call (steal) the Vehicle constructor so inheriting it\'s properties and methods.

\n
function Vehicle( colour ) {\n    this.purpose = "To move things from A to B.";\n    this.colour = colour;\n}  \n  \nVehicle.prototype.howManyWheels = function() {\n    console.log( "I\'m rolling on " + this.wheels + " wheels baby!" );\n}  \n  \nVehicle.prototype.whatColour = function() {\n    console.log( this.colour + " is the best colour by far!" );\n}  \n  \nfunction Car( manufacturer, model, wheels, colour ) {\n    // Call the parent constructor. Note we can now pass arguments too. Woop!\n    Vehicle.call( this, colour );  \n  \n    this.manufacturer = manufacturer;\n    this.model = model;\n    this.wheels = wheels;  \n  \n}  \n  \n// And we inherit the parent prototype\nCar.prototype = Object.create( Vehicle.prototype );  \n  \nCar.prototype.start = function() {\nconsole.log( "Nice " + this.manufacturer + " " + this.model + ", let\'s roll!" );\n};  \n  \nvar robin = new Car( "Reliant", "Robin", 3, "Risky Red" );  \n  \nrobin.start(); // Nice Reliant Robin, let\'s roll!\nrobin.howManyWheels(); // I\'m rolling on 3 wheels baby!\nrobin.whatColour(); // Risky Red is the best colour by far!  \n  \nvar veyron = new Car( "Bugatti", "Veyron", 4, "Storm Silver" );  \n  \nveyron.start(); // Nice Bugatti Veyron, let\'s roll!\nveyron.howManyWheels(); // I\'m rolling on 4 wheels baby!\nveyron.whatColour(); // Storm Silver is the best colour by far!  \n  \nconsole.log( Car.prototype.isPrototypeOf( robin ) ); // true\nconsole.log( Vehicle.prototype.isPrototypeOf( robin ) ); // true\n
\n

Prototypal Inheritance

\n

Whilst the Combination Inheritance pattern is very popular, JavaScript is a class-less language and we can implement inheritance perfectly well without classes or constructors. As we know, objects can inherit from other objects, which can in turn inherit from other objects, and so on. Not a class in sight! This form of inheritance is very easy to understand compared with some other patterns. We can use a mix of object literal notation and the Object.create() method to make our objects which makes our code easier to read. However we need to define every property of every object we create rather than just passing the values in as arguments to a constructor.

\n
var vehicle = {\n    purpose: "To move things from A to B.",\n    colour: "Rainbow",\n    howManyWheels: function() {\n        console.log( "I\'m rolling on " + this.wheels + " wheels baby!" );\n    },\n    whatColour: function() {\n        console.log( this.colour + " is the best colour by far!" );\n    }\n};  \n  \n  \nvar car = Object.create( vehicle );  \n  \ncar.manufacturer = "";\ncar.model = "";\ncar.wheels = "";\ncar.start = function() {\n    console.log( "Nice " + this.manufacturer + " " + this.model + ", let\'s roll!" );\n};  \n  \n  \nvar robin = Object.create( car );\nrobin.manufacturer = "Reliant";\nrobin.model = "Robin";\nrobin.wheels = 3;\nrobin.colour = "Risky Red";  \n  \nrobin.start(); // Nice Reliant Robin, let\'s roll!\nrobin.howManyWheels(); // I\'m rolling on 3 wheels baby!\nrobin.whatColour(); // Risky Red is the best colour by far!  \n  \n  \nvar veyron = Object.create( car );\nveyron.manufacturer = "Bugatti";\nveyron.model = "Veyron";\nveyron.wheels = 4;\nveyron.colour = "Storm Silver";  \n  \nveyron.start(); // Nice Bugatti Veyron, let\'s roll!\nveyron.howManyWheels(); // I\'m rolling on 4 wheels baby!\nveyron.whatColour(); // Storm Silver is the best colour by far!\n
\n

Note that both of the above patterns make use of Object.create(). This method has only been a native to JavaScript since the definition of ECMAScript 5 (thanks to Douglas Crockford). This means the method is not available to older browsers such as IE8 or older. We can however create the method if it isn\'t already defined:

\n
if ( typeof Object.create !== \'function\' ) {\n    Object.create = function ( o ) {\n        function F() {}\n        F.prototype = o;\n        return new F();\n    };\n}\n
\n

Shadowing And Deleting

\n

So what happens if an object defines a property or method with the same name as that of one of its ancestors? The descendant\'s property or method would shadow the ancestor\'s and stop the chain lookup right there. Other objects that also inherit from the same ancestor but have not shadowed the same property or method, will still use that of the ancestor.

\n
robin.start = function() {\n    console.log( "Three wheels is the only way to travel!" );\n};  \n  \nrobin.start(); // Three wheels is the only way to travel!  \n  \nveyron.start(); // Nice Bugatti Veyron, let\'s roll!\n
\n

To allow an object to inherit the property or method again, we must do more than just set the value to null or undefined. The delete operator must be used to completely remove the shadowing property or method.

\n
delete robin.start;  \n  \nrobin.start(); // Nice Reliant Robin, let\'s roll!\n
', id:"/home/geoff/www/cornerpiece/geoffford.co.uk/src/pages/blog/12-01-2015-object-oriented-javascript-cheat-sheet/index.md absPath of file >>> MarkdownRemark",frontmatter:{date:"2015-01-12T11:33:21Z",path:"/blog/object-oriented-javascript-cheat-sheet",title:"Object Oriented JavaScript Cheat Sheet"}},next:{html:'

\n \n \n \n \n \n

\n

What Is AngularJS

\n

AngularJS is a MVW (Model/View/Whatever) JavaScript framework that extends HTML through additional markup and produces more expressive and readable code. Its packed feature set make it a firm favourite for anyone developing SPAs or complex JavaScript based front ends.

\n

Why AngularJS

\n

Declarative User Interface

\n

Through the use of AngularJS directives, filters and expressions we can build more declarative UIs. This means we don\'t have to get bogged down with how to bend and shape the DOM of a html template view to our will. We can just declare what we want and where. This not only reduces development time but also leaves us with clean, intuitive code.

\n

2-Way Data Binding

\n

The whole MVW or MVVM (Model/View/View-Model) approach that AngularJS is well known for is possible due to it\'s View-Model or Scope as it is referred to in these parts. An application\'s scope sits between its view and its controller. From one side the controller can add variables and functions to the scope which can in turn be used by (bound to) the view. Okay, so not that impressive right? However AngularJS can also bind the view, or to be more specific HTML form fields back to the scope. What does this mean? Live Preview baby! Any changes made to the model by the view will be seen by the controller. And vice versa, any changes made to the model by the controller will be immediately visible in the view. This means the scope model is considered the single source of truth.

\n

Performance

\n

One of the big advantages of the above is that it is all achieved without a page reload anywhere to be seen. After the initial page load of an AngularJS application, any changes to the view (model data, partial views, etc) are performed automatically. How does it do that you ask? You might imagine that AngularJS loads the DOM as a string and parses it, updating as it goes then returning the updated string back to the browser to reload the DOM. This wouldn\'t be very efficient however as every small change would require the whole DOM to be updated, again and again. What actually happens is that the AngularJS Compiler service traverses the actual DOM looking for directives and expressions and then links these elements to the scope. It achieves this by registering listeners to the elements and placing watches on the scope. Anything changes in either the view or the scope, the other is updated instantly without a complete reload of the DOM. End result? A very responsive, fast application.

\n

Dependency Injection And Testing

\n

An age old problem of testing lies with the dependencies of our code. If dependencies, such as a call to an API, are declared directly within the code itself, tests will forced to use the very same (and possibly production) API call. The problem here is that our tests need to use consistent data input so that the outcome of our code can be correctly predicted. In our example, using a call to a live API could provide data that has been modified between tests and so taint the expected outcome. We can of course mock the service with our own pre-set and consistent data (like a fixture), but how can we tell our code to switch services when testing? The easiest way of managing this is to inject the required service into our code module as a dependency. The code can then utilise whichever service we supply and so provide the flexibility we need. This approach doesn\'t only help with testing, it also makes our code infinitely more re-usable.

\n

Thankfully, AngularJS was built with testing and the Separation Of Concerns (SoC) principal in mind from the outset and implements dependency injection throughout. Everything from components such as services, directives and filters to controllers and even module config can receive an array of dependencies to be injected. Nice!

\n

...Oh And It Plays Nicely With jQuery

\n

AngularJS comes with a lite version of jQuery aptly called jqLite built in. So if you are a fan of jQuery selectors for example, you can continue to use these within your AngularJS code. Should you discover you need to use a full blown version of jQuery, just make sure it is loaded before AngularJS and it will be used instead of jqLite.

\n

Getting Started

\n

Download or link to the CDN of the latest version of AngularJS (1.3.8 at the time of writing) in our html template (index.html):

\n
<!DOCTYPE html>\n<html> \n<head>\n\t<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>\n</head>\n<body>\n...\n</body>\n</html>\n
\n

Modules

\n

In keeping with SoC, AngularJS applications are built in a modular fashion to promote code re-use and more maintainable and easily testable code.

\n

Let\'s create an example AngularJS application module (app.js):

\n
var app = angular.module( \'myApp\', [] );\n
\n

The first argument is the name of the module. The second is an array of dependencies to be injected (of which we don\'t have any in this basic example).

\n

Now we include the module file in our html template:

\n
<head>\n\t...\n\t<script type="text/javascript" src="app.js"></script>\n\t...\n</head>\n
\n

And finally we need to bootstrap the application using our very first built-in directive ng-app (more on directives later):

\n
<html ng-app="myApp">\n...\n</html>\n
\n

Let\'s Meet The AngularJS Family

\n

Expressions

\n

AngularJS allows us to bind JavaScript-like expressions directly into a html template. The expressions can perform numerical and string operations or can refer to a variable/model within the scope.

\n
<p>1 + 2 = {{ 1 + 2 }}</p>  \n  \n<p>Hello {{ customer.firstName }}</p>\n
\n

Controllers

\n

An application\'s business logic is defined within its controllers. We can define our application\'s behaviour here as well as set the initial state of the controller\'s new child scope.

\n

First we need to create a controller and attach it to our application module (app) using the controller() method. The first argument is where we define the name of the controller and the second is the controller\'s constructor function (along with its dependencies):

\n
var app = angular.module( \'myApp\', [] );  \n  \napp.controller( \'CustomerController\', [ \'$scope\', function( $scope ) {  \n  \n\t$scope.customer = {\n\t\tfirstName: \'Peter\',\n\t\tlastName: \'Parker\',\n\t\tphoto: \'pparker.jpg\',\n\t\tisMember: true\n\t};  \n  \n}]);\n
\n

As you can see above, we have also initialised a \'customer\' object within the controller\'s scope. In real world examples of course this sort of data would probably be provided by an API service (injected as a dependency of the controller) rather than hard coded like this.

\n

Also note that whilst we are adding our controller to the same file as the module here (app.js), you can and probably should define your controllers in separate files (to be covered in a later article).

\n

Now to access our controller\'s scope (and all the values, objects and methods etc. associated with it) from within a html template, we must attach the controller to some relevant html element using another of the AngularJS built-in directives:

\n
...\n<div ng-controller="CustomerController">\n\t<p>Dear {{ customer.firstName }} {{ customer.lastName }},</p>\n</div>\n...\n
\n

Note that we can only access the controller\'s scope from within the bound element. If we tried to place {{ customer.firstName }} anywhere outside of the div bound to the CustomerController, it would be ignored.

\n

Built-in Directives

\n

As we have already seen earlier, AngularJS comes ready to roll with built-in directives. These directives allow us to extend standard HTML to help us build web applications. All AngularJS built-in directives use the namespace \'ng\' at the start i.e. ngApp, ngController, etc. (note the camelCase here). However, when we use the directives in html the camelCase is substituted for hyphenation i.e. ng-app, ng-controller, etc.

\n

Below is a selection of some of the most commonly used directives:

\n

ng-app
Used to auto-bootstrap an AngularJS application and also defines the root element of the application by whichever element the directive is placed on (usually <html> or <body>).

\n
<html ng-app="myApp">\n
\n

ng-controller
As we saw earlier, this directive is used to attach an existing AngularJS controller to a element within the html template. Remember, the controller\'s scope will only be available within the element that it is bound to.

\n
<div ng-controller="CustomerController">\n...\n</div>\n
\n

ng-show / ng-hide / ng-if
All three of these directives accept an expression to be evaluated. The first two are self explanatory i.e. they will show or hide whatever element they are attached to if their expression evaluates to true. The ng-if directive is similar to these but with one main difference. Whilst ng-show and ng-hide merely use CSS to show/hide the element, ng-if actually removes the element (and its contents) from the DOM if its expression evaluates to false and recreates it if true.

\n
<div ng-if="customer.isMember">\n...\n</div>  \n  \n<div ng-hide="!customer.isMember">\n...\n</div>\n
\n

ng-click
Attaches a click handler to an element. When the bound element is clicked, the method passed to the handler is run. The method must of course first be defined in the controller and added to the scope.

\n
app.controller( \'CustomerController\', [ \'$scope\', function($scope) {  \n  \n\t$scope.updateCustomer = function() {\n\t\t...\n\t\tsome code to save the customer changes back to the API\n\t\t...\n\t};  \n  \n}]);\n
\n
<button ng-click="updateCustomer()">Save Changes</button>\n
\n

ng-src
The problem with dynamically setting the source of an <img> element is that the data in the scope won\'t be available for the browser to pre-load as AngularJS hasn\'t parsed the DOM yet. AngularJS provides a solution with the ng-src directive. As the <img> will initially have no src, no attempt will be made to pre-load. Once the DOM has been parsed, AngularJS can set the src.

\n

Won\'t work (well it might but only after an additional request):

\n
<img src="http://www.example.com/photos/{{ customer.photo }}" />\n
\n

Will work:

\n
<img ng-src="http://www.example.com/photos/{{ customer.photo }}" />\n
\n

ng-repeat
So far so good, but ng-repeat steps up the excitement levels! No? Just me then. This powerful directive lets us iterate over a collection of items, such as an array of objects, applying a template to each item. In other words, a big time saver.

\n

Let\'s say we have an array of fruit objects in a controller:

\n
$scope.fruits = [\n        {\n            name: \'Bananas\',\n            stock: 5\n        },\n        {\n            name: \'Apples\',\n            stock: 2\n        },\n        {\n            name: \'Oranges\',\n            stock: 3\n        }\n];\n
\n

Now we want to list those healthy snacks out in a html template along with the current stock level:

\n
<ul>\n\t<li ng-repeat="fruit in fruits">{{ fruit.name }} ({{ fruit.stock }})</li>\n</ul>\n
\n

Yep that\'s it! I told you it was cool. We attach the ng-repeat directive to the element we wish to replicate for every item, for example the <li> element. Each item in the fruits array from our controller scope is assigned its own scope, in this case named fruit. We can then insert our AngularJS expressions to place our data where required.

\n

Outputs:

\n\n

Filters

\n

Once again AngularJS gets us started with a bunch of built-in filters that allow us to create subsets of, limit, order or format the output of an expression. They are preceded by the | symbol (to pipe our data through the filter) followed by the filter component name. This is then followed by a : and any filter arguments.

\n
{{ expression | filter:arguments }}\n
\n

Here is a selection of a few of them:

\n

currency
Format the expression to a currency with the provided symbol:

\n
{{ 1234 | currency:"&pound;" }}\n
\n

Outputs: £1,234.00

\n

date
Formats the expression (a date object, or milliseconds for example) to the provided date format:

\n
{{ 1420070401000 | date:"dd/MM/yyyy HH:mm:ss" }}\n
\n

Outputs: 01/01/2015 00:00:01

\n

filter
Creates and returns a subset array from the provided filter expression array (such as an array of objects used in a ng-repeat) based on the expression argument (a string, a pattern object or a predicate function). Let\'s use our earlier ng-repeat example and apply a couple of different filters.

\n

String example:

\n
<ul>\n\t<li ng-repeat="fruit in fruits | filter:\'an\'">{{ fruit.name }} ({{ fruit.stock }})</li>\n</ul>\n
\n

Outputs:

\n\n

Pattern Object example:

\n
<ul>\n\t<li ng-repeat="fruit in fruits | filter:{ name:\'es\', stock:3 }">{{ fruit.name }} ({{ fruit.stock }})</li>\n</ul>\n
\n

Outputs:

\n\n

Predicate Function example (requires the function to be defined in the controller\'s scope):

\n
$scope.filterByLowStock = function(fruit) {\n\treturn fruit.stock < 5;\n};\n
\n
<ul>\n\t<li ng-repeat="fruit in fruits | filter:filterByLowStock">{{fruit.name}} ({{fruit.stock}})</li>\n</ul>\n
\n

Outputs:

\n\n

Custom
Once you get the hang of the built-in offerings, have a go at creating your own custom filter.

\n

Forms & Models

\n

There was a significant omission from the earlier introduction to AngularJS built-in directives by the name of ng-model. This directive is the final piece in the 2 Way Data Binding puzzle and let\'s us bind html form fields to a model defined in the controller\'s scope. Assuming we use the earlier defined CustomerController, let\'s take a look at a basic example:

\n
<p>Customer name: {{customer.firstName}} {{customer.lastName}}</p>  \n  \n<form>\n\t<input type="text" ng-model="customer.firstName" />\n\t<input type="text" ng-model="customer.lastName" />\n</form>\n
\n

As you can see we have used ng-model to bind a couple of input fields to properties of our customer object. We are also displaying these properties above to illustrate the live preview. Now if we change either of the input field values (note the default value is set from the existing initialised model), this will update the model (customer object) in the scope which will in turn update the view and display our changes above.

\n

Note that there is no data retention at this stage. A refresh of the page and we are back where we started. This would require a function to be defined in the controller that saves our changes back to data source such as an API. Check out the ng-click example above for how we might go about this.

\n

Wrap Up

\n

Hopefully you now have a good understanding of the what, why and the beginnings of the how of AngularJS and feel inspired to have a go yourself. Tweet me up and let me know how you get on.

\n

I have planned a bunch of follow up articles to delve further into AngularJS so check back soon.

',id:"/home/geoff/www/cornerpiece/geoffford.co.uk/src/pages/blog/29-12-2014-angularjs-essentials/index.md absPath of file >>> MarkdownRemark",frontmatter:{date:"2014-12-29T17:55:15Z",path:"/blog/angularjs-essentials",title:"AngularJS: The Essentials"}}}}}}); //# sourceMappingURL=path---blog-javascript-cheat-sheet-eebb85bf7a1c1dbbfe1c.js.map