DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim...

18

Transcript of DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim...

Page 1: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework
Page 2: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

Discover AngularJSA step by step tutorial for beginners only

Adam Burak

This book is for sale at http://leanpub.com/discoverangularjs

This version was published on 2014-11-10

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishingprocess. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools andmany iterations to get reader feedback, pivot until you have the right book and build traction onceyou do.

©2014 Adam Burak

Page 3: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

Contents

About . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Structure of this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1The code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3What’s Angular? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Single Page Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3The challenges with SPAs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3How to get Angular? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Scratching the surface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Including angular . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Using our first directive: ng-app . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Main module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Creating a controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7ng-controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Using the $scope to expose data to the view . . . . . . . . . . . . . . . . . . . . . . . . . . 8Binding by using an expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Two way data binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11ng-repeat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

Page 4: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

AboutStructure of this book

The aim of this e-book is to get you started with the Google powered front-end frameworkAngularJS. The learning process will be phased over 2 parts:

Scratching the surface

This part is a quick tour of the main features of AngularJS. We will be explaining them throughextremely simple examples that you can run right away in Plunker. The objective is that by the endof it, you should have a simple but clear picture of how various AngularJS components fit togetherto make a web app.

Building an app

After the crash course, we are going to build, step by step, a simple but fully-fledged mobile webapplication showcasing all the previous angular features and new ones. The app we will be buildingis a simple counter that counts stuff: cups of coffee, beers taken in a day…etc. The app will rely on aremote API, but that should remain a black box, what matters is how to take advantage of a RESTAPI using AngularJS.

You can play with the demo using your mobile phone here:https://my-counters.herokuapp.com/

And of course it will also work on bigger devices (tablets or desktops) but it will look stretched.

This e-book does not pretend to be a touchstone of Angular’s best practices and doesn’t try to beone. Instead, it can be considered as a gentle introduction to Angular, giving you the confidence totackle advanced aspects of the framework.

Intended audience

This document has been written to fit readers that have at least a basic experience with JavaScript inthe browser, a basic understanding of what a Restful API is and ideally have tried to make a simpleweb app using a library like JQuery or something like it.

Page 5: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

About 2

The code

Part one makes use of examples made in Plunkers. The links to these plunkers are given to you asyou progress. The code of part two is divided by steps, and you can find it in Github:https://github.com/discoverangular/myCountersApp

Page 6: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

IntroductionWhat’s Angular?

Before we dive into technicalities, let’s try to understand what kind of tool Angular is and what itis capable of. Simply put, Angular is a JavaScript client-side framework that helps you build singlepage web applications (SPAs). But what are SPAs?

Single Page Applications

A SPA is a web app in which the browser doesn’t have to reload the page to go to another one. Theway it is done is by having a “shell page” where the other pages (aka views or partials) of our appwill be loaded via Ajax calls and then injected into a placeholder, like the body element.

Angular, as we’re going to see, makes working with SPAs effortless, and you should be glad it cando that because coding a SPA without Angular or any other capable framework is not trivial.

The challenges with SPAs

The hurdle with building SPAs from scratch is that there are a lot of concerns to deal with like:

• Manipulating the DOM programmatically when your views need to be updated because somedata has been changed.

• View loading.• Routing and managing history because you need to keep track of where you are and whereare you going.

• Marshaling data from the server to an internal object to your UI.• How to organize your code.

All of these common tasks and more are built into Angular making it a complete client-side solution.You don’t have to rely on a multitude of specialized libraries and worrying about those differentlibraries versions working together nicely in the future.

Moreover, even if Angular is typically used to make SPAs, you can use it even when you don’t havethe need to load views with it. You could just use it for the way it organize your code and the wayit guide you through the journey of building your app.

We can still say a lot about what Angular can do and explain what does working the “Angular way”means, but for a beginner that wouldn’t make a lot of sense. You can only have the “aha moment”looking backward.

Page 7: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

Introduction 4

How to get Angular?

Angular is available at angularjs.org

It’s a single JavaScript file that you can download through:

• The package manager Bower• Google’s CDN• Normal file download using your browser

The version we will be using throughout this book is v1.3.1.

What you are getting here is the core module of Angular; however, later in this book we will beusing other official modules that used to be in the core module but now are downloaded separately.

For a deployed application it is recommended to use a CDN; when you source the Angular scriptfrom Google’s CDN (Content Delivery Network) in your production ready app you get advantageslike better caching, decreased latency and increased parallelism; you can find more info about CDNadvantages at angularjs.org

As for browser support, Angular is supported in Safari, Chrome, Firefox, Opera 15, IE9 and mobilebrowsers (Android, Chrome Mobile, iOS Safari).

Page 8: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

Scratching the surfaceYour first contact with Angularjs will be through implementing a very simple application:

We will be displaying a string value! That’s it; it will be our Hello world!

We will be working with 3 files:

• index.html: the html code of our only and unique view• app.js: the JavaScript code of our app• And of course Angular

As mentioned earlier, all the examples are given as Plunkers which is really convenient since youdon’t have to type anything; however it’s recommended to play with the code given, adding andremoving bits to it is the way to learn.

Including angular

First thing is to include the Angular script file into this blank minimal html page. It’s not going todo much right now. Right after it, we also include app.js which is empty at the moment:

–index.html

1 <html>

2 <head>

3 <script src="path/to/angular.js"></script>

4 <script src="path/to/app.js"></script>

5 </head>

6 <body>

7 </body>

8 </html>

Using our first directive: ng-app

Like said earlier, in pretty much all your SPAs built with Angular, you will typically have onemain html file (we called it index.html) that will act like a “shell page”, where reside the <html>element and where you include Angular, just like the basic html page above; And because it’s a

Page 9: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

Scratching the surface 6

SPA, your other application’s pages will be injected on demand by Angular in index.html, right intoa placeholder like the body element for example.

We will later explain how to load different views with Angular, but for this example the shell page(index.html) will be our one and only view.

In order to get auto-bootsraped Angular needs to know the root element of the application which istypically the <html> or the <body> element which again only resides in your index.html

To do that, we add the ng-app attribute on the html element:

–index.html

1 <html ng-app="myApp">

2 ...

3 </html>

This was your first usage of what we call an Angular directive.

Simply put, Angular directives are a way of extending html whether by:

• Adding attributes on standard html element like <html>, <div>…etc. to make these elementdo more cool stuff.

• Defining a new type of element like a <myDatePicker></myDatePicker>

You can also write custom ones and get third party ones.

At this point, all what you need to know is how we use them, which is adding them right into yourHTML code. Basically, from a user point of view, directives are just HTML.

So to sum up, in your entire Angular app, you will have one main html file, index.html, where youspecify, using the ng-app directive, the root element of your application, which is typically <html>or <body>.

Main module

At this point, you’re probably wondering about the “MyApp” part in: ng-app="myApp".

Well, when putting the ng-app attribute on the html element, we typically also specify the name ofour main module. But what is a module?

In Angular, a module as an abstract concept is simply a container where the JavaScript code of yourapp resides. And it’s called a module because it makes applications modular; we can define multiplemodules that uses each other and also use third-party ones. Now, a main module is your applicationentry point, which you designated earlier like this: ng-app=”myApp”.

And concretely a module is merely a JavaScript object and this is how we define one:

–app.js

Page 10: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

Scratching the surface 7

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

It’s really, really simple to create a module.

Once you’ve included the Angular script, you’re going to have access to the angular object which ispart of the core Angular API. You can see that I called my module myApp the same name I put asthe value of the ng-app attribute.

But what about the empty array in the second argument? Well this is where you list all the othermodules that your application relies on, if any. Here’s an example of that:

–app.js

1 var app = angular.module('myApp', ['animationModule','helperModule']);

What I’m doing here is telling Angular to go fetch those modules and make them available to myentire application.

Of course your modules JavaScript Files has to be already included just right after you includedangular:

1 ...

2 <script src="path/to/angular.js"></script>

3 <script src="path/to/module1/module1.js"></script>

4 <script src="path/to/module2/module2.js"></script>

5 ...

Creating a controller

If you remember, what we are trying to achieve is displaying the string value “Hello World”.

That value must be defined somewhere, right?

To do that let me introduce you to another concept: Controllers!

The way it works in Angular is that you have a view, which is what we have so far in index.htmland then we have the JS code that drives that view. That JS code lives in another container called acontroller which itself is binded to a module. This is how we define one in our main module:

–app.js

Page 11: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

Scratching the surface 8

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

2 app.controller('myController', function() {

3 //my controller’s code

4 });

We used the module.controller() method. The first argument is the name of the controller, andin the second argument we pass a function called the controller’s constructor function where ourcontroller’s logic will reside. In our case this is where we will be defining our famous “hello world”.

Moreover, the controller doesn’t know anything about the view; it’s loosely coupled with it. It meansthat you can have a mobile view and a desktop view and they should work fine with the samecontroller. So one controller can be used for many views; furthermore, each parts of a view can bedriven by a different controller, but typically we prefer to couple a view with one controller.

ng-controller

What we need to do now is to the link our controller to its corresponding view. An elegant way tothat is by using the ng-controller directive like this:

–index.html

1 ...

2 <body ng-controller="myController">

3 ...

4 </body>

5 ...

Now this part of our view will be exposed to all the good stuff of our controller.

Using the $scope to expose data to the view

As said before, a controller contains all kind of code that drives our view like data and callbackfunctions for buttons. However not everything defined in the controller get to be available in theview. To expose, let say a value defined in our controller, we need to bind it to an object called$scope. Let’s do that in our controller:

–app.js

Page 12: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

Scratching the surface 9

1 ...

2 app.controller('myController', function($scope){

3 $scope.myValue = 'Hello World';

4 var myOtherValue = 'this one is not accessible in the view';

5 });

What should be curious to you is what is $scope? Why is it in the constructor function’s arguments?And where does it come from?

Simply put, scopes are special objects created and maintained by AngularJS in which you storeyour view’s model, aka data. In other words, a controller can expose objects and methods to a viewby binding them to the $scope object that we ask Angular to inject in the controller’s constructorfunction.

Everything on the $scope object is accessible in the corresponding View.

Now, passing $scope as a parameter in the controller’s constructor function is how we ask Angularto inject a $scope object and make it available in that function. This pattern is called dependencyinjection.

Simply put, dependency injection is a software design pattern in which one or more dependenciesare injected, or passed by reference, into a dependent object.

Angular has an injector subsystem which is in charge of creating components, resolving theirdependencies, and providing them to other components as requested.

From a simple user point of view, here’s another use case of dependency injection: You do rememberthat our application can make use of other modules like this:

var app = angular.module('myApp', ['animationModule','helperModule']);

However, to actually use, let’s say Feature1 from animationModule this is how we do it:

–app.js

1 app.controller('myController', function($scope, Feature1) {

2 $scope.myValue = 'Hello World';

3 var foo = Feature1.doStuff();

4 });

We just pass in as a parameter the name, according to that module API, of the feature we want touse and Angular will inject it for us.

Page 13: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

Scratching the surface 10

Before we go on, I would like to point out that the way we defined controllers so far is totally correct,however if you would like to minify your code, the minifier will rename the dependencies passedin the controller’s construction function and hence makes the Angular injector unable to inject thedesired dependencies since it relies on the name of these dependencies.

To allow the minifier to rename the constructor function parameters and still be able to inject theright dependencies, Angular provide a second annotation style:

1 someModule.controller('myController', ['dependency1','dependency2', function(dep\

2 endency1,dependency2) {

3

4 }]);

Here, instead of simply providing the constructor function, we pass an array whose elementsconsist of a list of strings (the names of the dependencies) followed by the function itself with thedependencies passed again as arguments.

Using this notation, our controller becomes:

–app.js

1 app.controller('myController', ['$scope', function($scope) {

2 $scope.myValue = 'Hello World';

3 }]);

We’ll be using this style for the rest of this book.

Finally, you probably are curious about the dollar sign in front of scope. To prevent accidental namecollision, Angular prefixes names of some of its built-in objects andmethods which could potentiallycollide with your code, with $. So please do not use the $ prefix in your code as it may accidentallycollide with Angular’s code.

Binding by using an expression

Great! So now what’s left to do is to display myValue in the view. To do that we are going to use apowerful Angular feature: Expressions!

Here is how we use expressions:

–index.html

Page 14: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

Scratching the surface 11

1 ...

2 <body ng-controller="myController">

3 {{myValue}}

4 </body>

5 ...

Yes, it’s that simple! The syntax of expressions is {{Expression}}.

If myValue wasn’t binded on the $scope, hence not be exposed to our view, that wouldn’t work.

We can do even more with expression:

{{1+1}} would print 2 in the view.

{{foo+bar}}would print the result of the evaluation of foo+bar, given that foo and bar are 2 variableson the $scope.

Ok, now you might be thinking: sweet! It looks like I can put any JS code in an expression and it willbe parsed and interpreted by Angular. Well, no and you shouldn’t be putting any advanced logiccode in your view. Expressions are mainly for binding data that’s on the scope, plus some othersimple features that you will discover later.

Here is the Plunker of our hello world app: http://plnkr.co/edit/wqUvooPECT34rZGiTL1m

Two way data binding

You are probably thinking that what we have done so far is not that impressive, and still waiting forthat part where you say wow that’s awesome! Well, just be patient.

Let’s go back to our view, and add a text input:

–index.html

1 ...

2 <body ng-controller="myController">

3 {{myValue}}

4 <input type="text" ng-model="myValue">

5 </body>

6 ...

As you can see we also used a new directive on it: ng-model.

The ngModel directive binds an input, select, textarea or a custom form control to a property on thescope.

In our case, we bind the myValue property to the input. If you run this, you will notice that “HelloWorld” is also displayed in the input just like with our expression data binding; but what’s more

Page 15: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

Scratching the surface 12

cool is that as we type in the input the value displayed by the expression change too automatically.That is called two way data binding.

Here is the Plunker: http://plnkr.co/edit/coNSyfPBGvMfU9sKa2Yx

Two way data binding means that “any changes to the view are immediately reflected in the mod-el/$scope, and any changes in the model are propagated to the view. The model is the single-source-of-truth for the application state, greatly simplifying the programming model for the developer.”

Thanks to the 2 way data binding, when you typed in the input you actually changed the valueof the $scope.myValue (changes in the view are reflected in the model) then, as you type, the newvalue is also displayed in the expression binding, since it also bind to the same property (changes inthe model are reflected in the view):

Moreover, binding with ng-model is little different than expression: when you bind a value to aninput and that value doesn’t exist already on the scope, Angular create it for you in the corresponding$scope object. If you delete the $scope.myvalue="Hello word" in our previous example, everythingwill still work fine.

If you came from a JQuery background, you would know how annoying it is to update parts ofyour html whenever some JS data change and vice-versa; and therefore you will understand howamazing this instant synchronization between the model and view is done in Angularjs. You bindonce through expressions and directives like ng-model and whatever changes happened in yourmodel, they will be automatically reflected in your view.

ng-repeat

Before we get to talk about another Angular component, I want to show you another commondirective. Let’s say I have an array on my $scope:

–app.js

Page 16: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

Scratching the surface 13

1 ...

2 app.controller('myController', ['$scope', function($scope){

3 $scope.rockBands = [

4 {name:"Aerosmith", frontman:"Steven Tyler"},

5 {name:"Guns ‘n’ Roses", frontman:"Axl Rose"},

6 {name:"U2", frontman:"Bono"},

7 {name:"The Rolling Stones", frontman:"Mick Jagger"},

8 {name:"Queen", frontman:"Freddie Mercury"}

9 ];

10 }]);

And what we want is to display the array in our view. At this point, it should be clear that theway we bind/display data exposed by the $scope object is only through directives or expressions; toiterate through an array of items, there is a directive for that called ng-repeat, and this is how it isused:

–index.html

1 ...

2 <body ng-controller="myController">

3 <ul>

4 <li ng-repeat="band in rockBands">

5 {{band.frontman}} - {{band.name}}

6 </li>

7 </ul>

8 </body>

9 ...

We just put it on the element we want to repeat along the array (in this case a li) and inside therepeated element we have access to the current item which is band so we can then display it usingan expression.

If you already have an experiencewith a templating language, youwill notice that HTML augmentedwith directives can act like one. Well that’s one of the many things that make working with Angularso clean and elegant, no need to learn a templating language.

Here is the Plunker: http://plnkr.co/edit/MaLxIGk96xo22XmrD3gV

Filters

What we can also do with Angular is that we can apply filters on simple values like strings or evenarrays. Filters are a way of formatting values. Angular’s core API contains built-in filters and youcan even make ones of your own. Let’s apply a built-in filter in Angularjs that will uppercase our“Hello World”:

–index.html

Page 17: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

Scratching the surface 14

1 ...

2 <body ng-controller="myController">

3 {{myValue | uppercase}}

4 </body>

5 ...

The syntax is very simple: {{expression | filter}}

We can also apply multiple filters, by chaining them: {{expression | filter1 | filter2 | ...}}

And finally, filters may have arguments:{{expression | filter:argument1:argument2:...}}

What’s also cool is that we can also apply the same filter with JavaScript in the controller; you simplyneed to inject a dependency with the name $filter to your controller and use it like in the followingexample:

–app.js

1 app.controller('myController', ['$scope', '$filter', function($scope, $filter) {

2 $scope.myValue = 'Hello World';

3 $filter('lowercase')($scope.myValue) ;

4 }]);

And as said before, we can also apply filters on arrays. Here we apply the orderBy filter that takesas an argument the property by which the sorting is done:

–index.html

1 <body ng-controller="myController">

2 <ul>

3 <li ng-repeat="band in rockBands | orderBy:'frontman'">

4 {{band.frontman}} - {{band.name}}

5 </li>

6 </ul>

7 </body>

Pretty cool huh? Here is the Plunker: http://plnkr.co/edit/4llnK8B6YqA15oAyoeIA

And finally let’s use a filter called filter that “selects a subset of items from array according to apredicate and returns it as a new array”. The filter filter can be used in different ways (cf the APIdoc) but we’ll showcase it here in a simple manner; we simply want to select items that contain thestring “rose”:

–index.html

Page 18: DiscoverAngularJSsamples.leanpub.com/discoverangularjs-sample.pdfAbout Structureofthisbook The aim of this e-book is to get you started with the Google powered front-end framework

Scratching the surface 15

1 ...

2 <body ng-controller="myController">

3 <ul>

4 <li ng-repeat="band in rockBands | filter:'rose'">

5 {{band.frontman}} - {{band.name}}

6 </li>

7 </ul>

8 </body>

9 ...

We can also pass in a variable as the argument, what about $scope.myValue that is binded to aninput:

–index.html

1 ...

2 <body ng-controller="myController">

3 <input type="text" ng-model="myValue">

4 <ul>

5 <li ng-repeat="band in rockBands | filter:myValue">

6 {{band.frontman}} - {{band.name}}

7 </li>

8 </ul>

9 </body

10 ...

Now as you type in the input, the array is instantly filtered with items that contain the typed value.Everything is auto-magically wired together!

Here is the Plunker: http://plnkr.co/edit/TE8EYw6mcOlYkSVe9yFW