AngularJS Programming Cookbook AngularJS Programming Cookbook i AngularJS Programming Cookbook ii Contents 1 2 3 Single Page Apps 1 1.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Setting up AngularJS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.3 The HTML markup of our app . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.4 Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 AngularJS Form Validation 5 2.1 View Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 2.2 Controller’s Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 2.3 Demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 2.4 Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 AngularJS Routing 9 3.1 What is routing in a web app . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 3.2 Today’s example’s concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 3.2.1 4 Defining the module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3.3 Demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3.4 Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 AngularJS Controller 4.1 13 Required Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 4.1.1 What are scopes? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 4.1.2 What are controllers? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 4.1.2.1 How to initialize the state of a $scope object . . . . . . . . . . . . . . . . . . . . . . . . . . 13 4.1.2.2 A small example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 4.1.2.3 Controllers’ use case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 4.2 Our Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 4.3 Demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 4.4 Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 . . .1. . . . . . . . . . . 27 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 5.4 Download . . . . . . 18 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Download . . . . . . . . . . . 25 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . . . . . .1 The JSON file . . . . . . . . . . . . . . . . . . . . . . .4 Download . . . . . . . . . . . . . .3. . . . . . . . . . . . . . 22 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 What you need to know . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 5. 18 The Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 8.2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Introduction . . . . . . . . . . . . . . . . . . . . .2 Example’s concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 The concept . .1 5. . . . . 28 AngularJS Data Binding 8. . . . . . . . . . . . . . . . . . . . . . . . . .3 Demo . .2. 20 5. . . . .1 Loading JSON into $scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 6. . . . . . . . . . .2 6 7 8 iii 18 Introduction . . 29 8. . . . . . . . . . . . . . . . . . . . . . . . . 18 5. . . 21 AngularJS Table 22 6. . . . . . . . . . . 29 8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 The app itself . . . . . . . 26 7. . . . . . .2 Our Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 8. . . . . . . . .3.1. . . . . . . . . . . . . . . .1 Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 The Example . . . . . . . . . . . . . . . . . . . .2 Displaying JSON data into a table . . . . .3 The Example . . . . . . .1. . . . .1 29 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 8. . . . . . . . . . . . . . . . . . .2 Example’s concept . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 What is JSON . . . . . . . . . . . . . . . . . . . . . . . . 21 5. . .1. . . . . . .2 ngModel . . . . . . . . . . . . . . 24 AngularJS ng-src 25 7. . . . . . . . . .3 Demo . . . . . . 29 8. . . . . . . . . . . . . .4 Demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .AngularJS Programming Cookbook 5 AngularJS JSON Fetching 5. . . . . . . 31 . .2. . . . . . . . . . . . 26 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3. . . . . .1 Introduction . . . . . . . 19 5. . . . . . . . . . . . . . . . . . . . .2 Fetching the JSON file . . . . . . . . . . . .1. . . . . . . . . . . . . . 18 5. . . . . . . . . . . . . . . . . . . . . .3 Demo . . . . . . .2. . . . . . . . . . . . 25 7. . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 The JSON file . . . .3 Displaying the JSON file . . . . . . . . . . . . . . . . . . . . . . . . or transmitted. no part of this publication may be reproduced.C. photocopying. in any form or by any means (electronic. mechanical.. recording or otherwise). iv . Without limiting the rights under copyright reserved above. 2015 All rights reserved.AngularJS Programming Cookbook Copyright (c) Exelixis Media P. stored or introduced into a retrieval system. without the prior written permission of the copyright owner. from Single Page Apps and Routing.org/wiki/AngularJS) In this ebook. (Source: https://en. you will be able to get your own projects up and running in minimum time. With our straightforward tutorials. The values of those JavaScript variables can be manually set within the code. to Data Binding and JSON Fetching. It aims to simplify both the development and the testing of such applications by providing a framework for clientside model-view-controller (MVC) and model-view-viewmodel (MVVM) architectures. or retrieved from static or dynamic JSON resources. which has embedded into it additional custom tag attributes. . Angular interprets those attributes as directives to bind input or output parts of the page to a model that is represented by standard JavaScript variables. The AngularJS library works by first reading the HTML page. along with components commonly used in rich Internet applications. we provide a compilation of AngularJS based examples that will help you kick-start your own web projects.wikipedia. We cover a wide range of topics.AngularJS Programming Cookbook v Preface AngularJS (commonly referred to as "Angular") is an open-source web application framework maintained by Google and by a community of individual developers and corporations to address many of the challenges encountered in developing single-page applications. WCGs serve the Web designer.AngularJS Programming Cookbook vi About the Author WCGs (Web Code Geeks) is an independent online community focused on creating the ultimate Web developers resource center.com/ .webcodegeeks. technical team lead (senior developer). targeted at the technical architect. articles. You can find them online at http://www. project manager and junior developers alike. reviews. tutorials. announcements. code snippets and open source projects. Web developer and Agile communities with daily news written by domain experts. . but we will be using Angular as it is a structural framework for dynamic web-apps. but have it reflect them immediately. an HTML file named index. We will use: • AngularJS • Bower • Twitter’s Bootstrap 1. an about page and a date page.js inside of it.html and a Javascript file named app.AngularJS Programming Cookbook 1 / 31 Chapter 1 Single Page Apps Single Page Apps are becoming increasingly popular as the demand for highly responsive apps is increasing.2 Setting up AngularJS First we ask Bower to install the Angular package by executing this in the terminal (make sure you’re in your project’s directory): bower install angular Then. efficient and easy to use.js and write the JavaScript code for creating the Angular module. again using Bower we install the Angular-Route package by executing: bower install angular-route After executing these commands we will notice that in our project’s directory a bower_components directory is added. We could be using Ajax and Javascript to do this. and we’re good to go.1 Getting started To go on with the project you might want to download Bootstrap and also Bower (here you will find every information you need on how to do that).module(’app’. we create a folder named SinglePageApp (you can name it anything you wish). Then we open the app. one named angular and one named angular-route. while adding ngRoute dependency to it. inside of which are two folders. 1. It should look like this: var app=angular. as described by the people who built it.[’ngRoute’]). Firstly. so as to not need to refresh the page to view changes. We will use them later. We’re going to create a simple app with only a homepage. controller(’About’.{ templateUrl : ’pages/about.homepage = "Homepage". and inside of it we create a JavaScript file named controllers.controller(’Homepage’. function($scope){ $scope.controller(’Date’. starting from index.min. First we link Bootstrap’s CSS file by adding this right under the </title> tag: <link rel="stylesheet" href="css/bootstrap.min. Right under the code for the angular module. controller : ’Date’ }).js"></script> . First we create a directory named controllers in the js folder.3 The HTML markup of our app An important thing to do if we want our app to function properly is to link and script all the files we’ve downloaded. We have injected $routeProvider as a parameter to the function. We will use only two of those properties: the templateURL which is a relative location of the view file. Now the when() function of the $routeProvider can be used to configure the routes.when(’/about’.js"></script> <script src="bower_components/angular/angular. provided by angular.js where we will put this code snippet: app. }]).[’$scope’. You can even place the above code in the app.js file but it is not recommended as it could reduce the readability of the code and in heavier applications could complicate stuff.module.html’. 1.{ templateUrl : ’pages/homepage..css"> Now let’s script Bootstrap’s.[’$scope’.js in the index. }). controller : ’About’ }) //date page .".when(’/’. Angular’s and Angular-Route’s JavaScript files by adding this code after the <link> tag: <script src="js/bootstrap.html’.min. and the controller associated with the view. controller : ’Homepage’ }) //about page .min. We have reached the point where we should create the controllers for the different views.html’. function($scope) { $scope. }]). }]). Don’t forget to script the file controllers. in the app.html.{ templateUrl : ’pages/date.AngularJS Programming Cookbook 2 / 31 Now is time to define routes by using the config() function.[’$scope’.function($scope){ $scope. app..when(’/date’.now = new Date().js"></script> <script src="bower_components/angular-route/angular-route. app. This function takes two parameters: the route name and the route definition object which in itself contains various details for a route.js file we place this code: app.about = "Lorem ipsum.html file.config(function($routeProvider){ $routeProvider //default page . and place this code inside it: . as the whole page will be an ngapp it is better to place the attribute in the <html> tag or in the <body> tag. The About page will be a typical descriptive page. In the <body> section we will add the buttons.html file we will only place the {{homepage}} expression. In our case. numbers. only it has a # (hashbang) before it. Familiar? It is the route we specified when we used when() function. But where is the app going to display the views we created? We will tell it where. Time to have a look at index. You saw that when declaring the angular module we named it app. You may have noticed the "row" attribute I gave to the div containing the ng-view element. and controller. Now let’s create a directory named pages inside of which we will place the HTML files for the views. We will use Bootstrap to create them easily but also to make them look stylish. like this: <script src="js/app. This particular filter formats the date so as to show the month. minutes and seconds in AM/PM format. right before the </body> tag. and also the time in hours. sans-serif.row{ text-align: center. as the browser will render the HTML markup first and then the JavaScript code is loaded. Beware that the files for the views should not be complete HTML files. currency etc. so we will only need this code: {{ about }} The date page will show us the date of today. font-family: "Georgia". To make the website look a little more fancy. The code will go like this: <a href="#/"><button class="btn btn-danger">Homepage</button></a> <a href="#/about"><button class="btn btn-success">About</button></a> <a href="#/date"><button class="btn btn-warning">Date</button></a> Take a look at the href attribute in each of the links.Views go here --> </div > </div > I have placed it inside another div element. serif . To tell it where it should be active we add the attribute ng-app= "app" in the tag and everything inside of it turns into an AngularJS application. but is not recommended if your target users will use IE as it does not support the element version. AngularRoute gives it the opportunity to completely replace the <div ng-app> element with the element <ng-app> </ng-app>. Please bear in mind that the scripting of angularroute and app. font-size: 30px. by placing a `` element containing the attribute ng-view. Angular gives us several built-in filters as well as an easy way to create our own. The code will go like this: {{ now | date:’medium’ }} While by now you know that what we have placed inside the double curly brackets is an expression. background-color: steelblue.AngularJS Programming Cookbook 3 / 31 Also we script the app. a short way to format some of the most used expressions. I’m choosing the second.js. one for each view.css file inside the css folder (don’t forget to link it). they should only have the markup for the specific view. date and then the year. In the homepage. it is worth noting that | date:’medium’ is a filter. but you can place it anywhere in the application’s body. We will have to tell Angular in which part of the application it should be active.js should come after the scripting of app.js should come after the scripting of angular. for performance reasons. It will look like this: <div class="row"> <div ng-view> <!-. as it contains our angular module and also other necessary things.js file. such as dates. The class attribute you see in the <button> tags is a class provided by Bootstrap.html. you create a styling. It is there for styling purposes only. green for btn-success and orange for btn-warning).js"></script> You might want to place all this in the <body> section. } . which makes them look fancy and have specific colors (red for btn-danger. looking like this: Figure 1.4 Download Download You can download the full source code of this example here: SinglePageApp . without reloading the page.1: Single Page App when the About button is pressed.AngularJS Programming Cookbook 4 / 31 You can now open your Single-Page App and it will show you different views each time you click the buttons. 1. Such is the magic of AngularJS. is to attach a controller to our form.bootstrapcdn.e.2/css/bootstrap.email. Our example’s concept is that both of the form’s fields are required. username and email and two buttons. one for reset and the other with a submit role.</ ←span> <label>Email:</label> <input type="email" class="form-control" name="email" ng-model="email" ←required> <span ng-show="sampleForm. Suppose a form with two fields. Today’s example demonstrates a simple way to implement client-side validation using the AngularJS form properties.min.$error.username.js"></script ←> <script src="script.1 View Page The best way to take advantage of Angular’s abilities.2.com/bootstrap/2.js"></script> <link rel="stylesheet" href="style. so the form cannot be submitted if either of these is empty or has invalid format (i.googleapis.</span> <button class="btn btn-link" ng-click="reset()">Reset</button> . 2.com/ajax/libs/angularjs/1.required">Username is required.</span> <span ng-show="sampleForm.required">Email is required.html <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://maxcdn. according to form validation. the email).$error.$error.email">Invalid email address.26/angular.css"> <script src="http://ajax.css" > </head> <body> <h2>AngularJS Form Validation Example</h2> <form ng-controller="validationCtrl" name="sampleForm" novalidate> <label>Username:</label> <input type="text" class="form-control" name="username" ng-model="username" ←required > <span ng-show="sampleForm.email.3. index.AngularJS Programming Cookbook 5 / 31 Chapter 2 AngularJS Form Validation One of AngularJS advantages is the simplicity it provides for validating forms. ←min. using ng-click directive. In Angular. while the form is invalid (line 26). According to AngularJS. Finally. ←$invalid" ng-click="checkData()"> </form> </body> </html> As you make clear from the head’s definition.username = validUsername. On the other hand.com". A typical client-side validation process contains error messages.checkData = function() { if ($scope. such as $dirty or $invalid.bais@gmail. for the cases of invalid (email) or blank input fields. } else { alert("Seems to be ok!"). there are discrete form states. this means that we partially want extra messages to be displayed in our webapp. 2. which. } } } 2.reset = function(){ $scope. AngularJS provides the ng-show directive for this purpose. the submit buttons gets enabled. Generally. $scope. which will be nothing more than a handler for our form’s buttons. script. the glue between the application controller and the view.js will contain the controller’s logic. refer to the official documentation. your guess is right. We want our submit button to be disabled.2 Controller’s Functionality When our form has a valid state. the submit has to check if the form contains the correct data. results to the client-side validation. for user-interaction check with the form and for invalid input fields check. Line 12 declares clarifies that our form is attached to validationCtrl and yes. Lines 16 and 21-22 implement the validation in the AngularJS way.email != validEmail) { alert("The data provided do not match with the default owner"). in conjunction with the form’s states. AngularJS provides ng-disabled directive to make this feasible. $scope. } $scope. var validEmail = "thodoris. I decided to separate HTML from Javascript and CSS. is the $scope object.AngularJS Programming Cookbook 6 / 31 <input type="submit" class="btn btn-primary" ng-disabled="sampleForm.3 Demo Let’s run our app: . To read more about form properties. Suppose there is a predefined acceptable username and email from the webapp and that this the purpose of the reset button: to turn our form to its acceptable format. respectively.username != validUsername || $scope.email = validEmail. the script.js function validationCtrl($scope) { var validUsername = "Thodoris Bais". we clarify that we want our controller to run a specific function for each of the form’s buttons. here’s the job of ng-show: Figure 2.1: Initial screenshot of webapp After leaving the email field blank.AngularJS Programming Cookbook 7 / 31 Figure 2. we firstly notice that the submit button get enabled (both fields have now a green/valid border) : .2: Email cannot be blank Having provided the valid input data. AngularJS Programming Cookbook 8 / 31 Figure 2.zip .4 Download Download You can download the full source code of this example here: angularjs_form_validation.3: Providing valid data 2. bootstrapcdn. So.js"> ←</script> . We often confirm similar situations after interacting in the root of a web app ( / or index. suitable for an Angular newbie.2.1 What is routing in a web app Generally. we ll here implement an inline navigation. the anchors’ targets are already named. This means that we want our pages content to be displayed inside the initial/home page. What I firstly found out.min. the included view changes with it according to the configuration of the $route service.AngularJS Programming Cookbook 9 / 31 Chapter 3 AngularJS Routing This example is related with routing in AngularJS. Specifically. ngView directive complements the $route service by including the rendered template of the current route into the main layout file.3. Suppose a homepage with two links and each one of them will redirect to a specified page.com/bootstrap/3. keeping in mind that our index. I’ll try to keep today’s post as simple as I can. To get a better understanding of our concept. each time the current route changes. That is.html ). by noticing a change to the browser’s url bar. so what is left.2 Today’s example’s concept In this example we will demonstrate a simple page navigation application. this should seem like: Jump to the <a href="#first">first</a> or <a href="#second">second page</a> <div ng-view> As you see. that results to a different view on the client-side.googleapis.com/ajax/libs/angularjs/1. is that there isn’t yet any simple example. is to configure the respective routings for Angular.min. web applications make use of readable URLs that describe the content that resides there.html <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://maxcdn. at this point we should have a complete homepage: index. assume we want to display the rendered templates (according to the clicked links) below that sentence. 3.26/angular. AngularJS provides the ngView directive to implement the fore-mentioned functionality. So.css"> <script src="http://ajax. A common example could be clicking on a homepage’s link: this means that a back-end action is being executed.2/css/ ←bootstrap.html contains a simple sentence with two links provided. while searching over the net for similar resources. 3. So. has to be loaded. • The routings we need. we can use the ngRoute module for routing and deeplinking services and directives. That’s why we had to include the angular-route. the last words mean that we have to "inject" ngRoute into our module ( script. obviously.config(function() { }).2.googleapis.module(’RoutingApp’.js"></script> <script src="script.AngularJS Programming Cookbook 10 / 31 <script src="http://ajax.config method: angular.module(’RoutingApp’. [’ngRoute’]) .e. Here are some important points before going on: • In order to use the ngRoute module.config( [’$routeProvider’. ’cause. so it would be easier to define our module in a separate file. have to be configured inside the module’s functionality. otherwise.com/ajax/libs/angularjs/1.config method requires calling it with a function. we can use the $routeProvider to configure Angular’s routes. In order to use ngRoute.js ). • You have to provide same name for the ng-app tag (in html file that contains the Angular app) and the module’s definition. [’ngRoute’]).module(’RoutingApp’.js. like this: angular. which. let’s define the Angular module. ←min. controller property is responsible for this scope). route): • path corresponds to the requested from the client path. after including the angular.1 Defining the module Now. • route is an object parameter and contains mapping information that have to be assigned while matching the requested route (i.js"></script> </head> <body ng-app="RoutingApp"> <h2>AngularJS Routing Example</h2> Jump to the <a href="#first">first</a> or <a href="#second">second page</a> </body> </html> In AngularJS. we ’ll get a script error from our browser.js script.js file in our app. you have to include angular-route. we may want to handle the newly registered route with a specific controller. function($routeProvider) { }]). . The $routeProvider’s method to add a new route definition to the $route service is when(path. 3.2. From the official documentation.js to your app. As you noticed. script. I also created an anonymous function inside the method. we have to call the angular.26/angular-route. by providing our app’s name (as in index. [’ngRoute’]) .html) and declaring that it depends on the ngRoute module. as angular. so we should pass $rout eProvider as a parameter in our anonymous function: angular. Please take a look at the module’s final structure: script.html’ }) . click on "first": . but as I fore-mentioned. this method will be executed. The $routeProvider’s otherwise(params) method sets route definition that will be used on route change when no other route definition is matched. { templateUrl: ’second. }]). Now.module(’RoutingApp’. In our case. so.3 Demo Firstly. function($routeProvider) { $routeProvider . here.html’ }) . when no route definition gets matched. 3. Access the web app from your local server: Figure 3. just to understand why you should deploy this app in a local server rather than just executing it in a browser. let me explain: the first when means that when the /first is requested as a route. Practically. { templateUrl: ’first.config( [’$routeProvider’.when(’/second’. we ’ll implement a simple routing between two html files.js angular.1: Homepage of the app Now.AngularJS Programming Cookbook 11 / 31 You can read about the rest of route’s object properties. I assume we want to display just the homepage (’/’).t defined in the when method.html will be loaded. I’ll only use the templateUrl.when(’/first’. Same for the "second". [’ngRoute’]) . that if the client requests a route that isn. please take a look at this post.otherwise({ redirectTo: ’/’ }). this means. Imagine this as a general if-else statement. the first. 3: App’s "second" page 3.2: App’s "first" page Same.AngularJS Programming Cookbook 12 / 31 Figure 3.4 Download Download You can download the full source code of this example here: angularjs_routing.zip . for the "second": Figure 3. they hold the Model data that we need to pass to View and use Angular’s two way data binding to bind model data to View. 4. All the $scope properties will be available to the template at the point in the DOM. Using a controller. This updates an informative message (i.1 How to initialize the state of a $scope object When creating an application. where the user is prompt to insert his username. we can instantiate a new child scope as an injectable parameter to controller’s function. This can be feasible by attaching properties to the $scope object. 4.1 Required Background Before getting into the technical part of this example. In addition.1.AngularJS Programming Cookbook 13 / 31 Chapter 4 AngularJS Controller Hello! In today’s example we ’ll see how do Angular’s controllers work. To get into this.1. where the controller is registered. let me introduce you the $scope element. It can be attached to the DOM through the ng-controller directive.1 What are scopes? AngularJS supports the MVC pattern. where Angular instantiates a new Controller object. we need to set up the initial state for the Angular $scope. an Angular controller is a JavaScript constructor function that augments the $scope object. it’s the glue between View and Controller. 4.1. which will be presented by the View). I chose a simple form concept. Their responsibility is to initialize the data that the View needs to display. which attaches a helloMessage property containing the string "Hello World!" to the $sc ope: .2. 4.2 What are controllers? Generally. I’ll also include a reset button. The injected parameter is accessible through $scope. These properties contain the View (the Model. 4.2 A small example We here create a HelloController. "Your username is ").1. In fact. for demonstration purposes.2.e. using the specified controller’s constructor function. with the $scope object associated with the application model. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. index.module(’myApp’. we attach our controller to the DOM using the ng-controller directive.css" > </head> <body ng-app="myApp"> <h2>AngularJS Controller Example</h2> <form> <label>Name:</label> .bootstrapcdn.googleapis. myApp.com/ajax/libs/angularjs/1. use angular form controls instead.js"></ ←script> <script src="script.2.helloMessage= ’Hello World!’. The helloMessage property can now be data-bound to the template: < div ng-controller="HelloController" > {{ helloMessage }} </div > 4. related to the controller’s logic.min.min. use angular services instead.3 Controllers’ use case Generally. This keeps the controller’s constructor function out of the global scope. [’$scope’.controller() method.com/bootstrap/2. Next. What is actually done. is an Angular module creation ( myApp ) for our app.2. using the . • Manage the lifecycle of other components (i. }]). We then add the controller’s constructor function to the module.[]). function($scope) { $scope.e.3.js"></script> <link rel="stylesheet" href="style.css"> <script src="http://ajax. to create service instances). with a reset button and an updateable message. • Share code or state across controllers.1.2/css/ ←bootstrap. • Format input. 4. Cases that we cannot use controllers are to: • Manipulate DOM (controllers should contain only business logic). use angular filters instead.26/angular.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>AngularJS Controller Example</title> <link rel="stylesheet" href="https://maxcdn. a username text field.controller(’HelloController’. • Filter output. we usually use controllers either to setup the initial state of the $scope object or to add behavior to the $scope object.2 Our Example As I fore-mentioned.AngularJS Programming Cookbook 14 / 31 var myApp = angular. there is the message that we earlier discussed. from Angular’s perspective.username). []). This is actually a directive that binds our text field to the username property on the scope. }. the text field will contain a predefined value.username = ’unknown’. where. We then define the controller’s name and initialize the username with the value of unknown.js file. we declare our Angular application in the name of myApp. script. That is.html. but on user change. At first. That is.e.3 Demo Let’s now display a quick demo. The ng-click directive will call the reset() function of our controller. [’$scope’. the text field’s value can be changed inside the controller. by accessing the username property from the scope object (i.AngularJS Programming Cookbook 15 / 31 <input type="text" class="form-control" name="username" ng-model="username" ←> <button class="btn btn-link" ng-click="reset()">Reset</button> Your username is {{username}} </form> </body> </html> As line 9 clarifies. the one named as myApp application. Let’s now code the Controller and then explain the necessary details. This is the initial view: . in general. What about line 19 and ng-click? Well.js var myApp = angular. }]).username = ’’. $scope. especially the one defined in our index. in line 18. In line 13. In line 21.module(’myApp’. Obviously. which is created and exposed by this directive. myApp. in conjunction with line’s 9 included script. when the reset button is clicked. 4. our controller’s functionality will be defined into the script. we bind the div element including its children to the context of UserController controller. we have to define that this script is about an Angular module. Lines 15-23 contain the important div which interacts with UserController (this. What else is important here. ngmodel interferes with the controller and updates the username’s value (the curly braces variable binded in the View). Enough said for our View’s implementation. function($scope) { $scope. is the ng-model attribute of the text field. means that our controller’s logic is contained int the javascript file.reset = function() { $scope. when the application is loaded to the browser. with the help of UserController. the reset function is used to empty the text fiel’s content. using the ng-controller directive.controller(’UserController’. $scope. the double curly braces notation ( {{ }} ) binds expressions to elements. which.1: Initial state of the app If we hit the reset button. in conjuction with the user input.2: The reset button Finally.AngularJS Programming Cookbook 16 / 31 Figure 4. result to a dynamic view in our application: Figure 4. our text field gets empty: Figure 4. here is the updated message.3: User input . AngularJS Programming Cookbook 4.zip 17 / 31 .4 Download Download You can download the full source code of this example here: angularjs_controller. record. struct.2 The app itself So. we ll here deal with countries population around the world. It is built on two structures: • A collection of name/value pairs.1. in a user-friendly way. In various languages. hash table. or associative array. 5. what’s the plan? • Fetch the JSON. Specifically.2 Example’s concept In this example we will demonstrate a simple way to retrieve a JSON file and display the respective information to our Angular application. keyed list.2. • An ordered list of values. vector.2. list. 5. It is easy for machines to parse and generate.1. • Display JSON’s information in a more human-readable way.AngularJS Programming Cookbook 18 / 31 Chapter 5 AngularJS JSON Fetching Hello there! Today’s example’s about displaying data from a JSON file to an Angular. like this: 5.1. .1.1 What is JSON JSON is a lightweight data-interchange format.js application. this is realized as an array. this is realized as an object. It is easy for humans to read and write. In most languages.1 The JSON file I have already prepared a countries json file. 5. which provides codenames and population data for several countries around the world. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers. or sequence. dictionary.1 Introduction 5. config) { // this callback will be called asynchronously // when the response is available }). please consult this post. Ok. in order to be accessible all over the app and yes. rather than executing it in a browser. error(function(data. headers. Here’s how a simple GET request looks like: // Simple GET request example : $http. the corresponding action will take place into the head’s script. so. It returns a promise with two $http methods: success and error. . let’s say "countries": $http. Practically. status. whereas the request data must be passed in for POST/PUT requests: $http. }). 5.get(’/someUrl’). what about the difficult one? The fore-mentioned "action" is actually a call to the $http service. headers.json’).countries = data. For further details about this fact. the $http core service.success(function(data) { $scope. $http) { $http.success(function(data) { $scope. success(function(data. here’s the updated format of our service call: countryApp.success(successCallback).2.get(’countries.countries = data. That is. }).get(’/someUrl’).AngularJS Programming Cookbook 19 / 31 Fetching the JSON at first.json’). function ($scope. status. assuming that we named our angular app as "countryApp". }).get(’countries. Obviously.controller(’CountryCtrl’. means that this has to be done each time the app is being loaded to the browser. we want to load our JSON file into a global variable. config) { // called asynchronously if an error occurs // or server returns response with an error status. your guess was right. a core Angular service that facilitates communication with the remote HTTP servers via the browser’s XMLHttpRequest object or via JSONP. please take a look at this post. provides shortcut methods. that was the easy part. this service call has to be a part of an Angular’s app controller definition. $scope is the global variable that we ’re searching for! In addition. we have to load our JSON file into a $scope variable. The general usage of the $http service is a single argument (configuration object) that is used to generate an HTTP request. }).2 The Example Time for action! 5. this means that you have to deploy your app in a web server. where the only requirement is the URL that has to be processed.1 Loading JSON into $scope According to the fore-mentioned notes. If you need further assistance according to Angular Controllers. We’ll only make use of the success and guess what?! On service’s successful call/execution. 3.js JSON Fetching Example</title> <link rel="stylesheet" href="https://maxcdn.population}}</td > < / tr> Here is the final structure of our app: index.com/bootstrap/3. countryApp. }).js JSON Fetching Example</h2 > <table > <tr > <th>Code</th > <th>Country</th > . }). []).name}}</td > < td>{{country.success(function(data) { $scope. • We want to divide each country’s data. which instantiates a template once per item from a collection. name.2. This fact is translated into two requirements: • We have to find a way to repeatedly parse all the data from $scope. in order to display each one in the corresponding table’s column Defining the table’s headers is very easy: <th>Code</th > <th>Country</th > <th>Population</th > </tr > Now.json’).module(’countryApp’.bootstrapcdn. where the given loop vriable is set to the current location item.AngularJS Programming Cookbook 5. In our case. </script> </head> <body ng-controller="CountryCtrl"> <h2>Angular.variables (as we obviously don’t want to exercise our handwriting for more than 70 separate countries).css"> <script src="http://ajax.2. let’s display them to a table with three columns: code. we ’ll use Angular’s ngRepeat directive. Each template instance gets its own scope. $http){ $http. name and population.2 20 / 31 Displaying JSON data into a table Now that we ’ve loaded all the JSON’s data into $scope.get(’countries.com/ajax/libs/angularjs/1.controller(’CountryCtrl’.html <html ng-app="countryApp"> <head> <meta charset="utf-8"> <title>Angular. into code.code}}</td > < td>{{country. and $index is set to the item index or key. to repeatedly loop over each country. to fullfil the first requirement. function ($scope. population.js"> ←</script> <script> var countryApp = angular.countries = data. we have to assume that each country is a table row: <tr ng-repeat="country in countries"> Fullfilling the second requirement is now easier. that the country processed each time can be accessed from the country variable: < tr ng-repeat="country in countries | orderBy: ’code’ "> < td>{{country.26/angular.2/css/ ←bootstrap.min.countries.min.googleapis. population}}</td > </tr > </table > </body> </html> 5.3 Demo Let’s run it in a local server.code}}</td > <td>{{country.name}}</td > <td>{{country.1: App screenshot 5.4 Download Download You can download the full source code of this example here: angularjs_json_fetching.AngularJS Programming Cookbook 21 / 31 <th>Population</th > </tr > <tr ng-repeat="country in countries | orderBy: ’code’ " > <td>{{country. Figure 5.zip . Besides the basic functionality that the $scope object provides. I here want to demonstrate a sample table implementation. let’s again separate our View from our Controller (MVC pattern). {"name": "Paul". too. Now that you have a basic understanding of scopes and cotrollers.html <html ng-app="tableApp"> <head> <meta charset="utf-8"> <title>Angular. "hobby": "Fishing"}.1 Introduction If you ’re not enough experienced with Angular. the model’s data is created into the controller. Let’s see the way over it! 6. accompanied with their hobbies. Having understood the MVC pattern. now that we know what our controller’s definition will contain. "hobby": "Football"}. like below: $scope.AngularJS Programming Cookbook 22 / 31 Chapter 6 AngularJS Table Hi there! Today we ’ll examine a simple table solution. Ok. "hobby": "Snooker"} ]. so.js Table Example</title> . not an MVC example. {"name": "George". {"name": "John". "hobby": "Gym"}. after it: index.1 and 1. we can also use it to handle an array with it. using the Angular.js file.js framework. That is. you should first take a glance at a previous example of mine. {"name": "Nick". is provided (paragraphs 1. let’s solve our problem! 6. we need our controller to pull the necessary data from the Model and "feed" the view with them. we ’ll provide our view in index. whereas the controller’s functionality will remain in script. in the gentle packaging of an HTML table.persons = [ {"name": "Thodoris". into the $scope object. "hobby": "Basketball"}. We can define an array of persons (with their names and hobbies).2 Our Example To begin with. html. where the required background for this example. instead of being pulled from the model. to make it easier for you.2). Suppose we want to display a list of persons. let’s see our view file and we ’ll get back to the definition of our script. {"name": "Paul". we have to assume that each person is a table row. and $index is set to the item index or key. we have to find a way to repeatedly parse all the data from the controller’s persons array to our table.js"></script> <script src="script.26/angular. []) . Each template instance gets its own scope.js"></ ←script> <script src="http://ajax. Lines 12 and 13 declare our table’s headers.com/ajax/libs/angularjs/1. where the given loop variable is set to the current location item. "hobby": "Gym"}. Now.googleapis. This results to an extra requirement. This means that our view will search for the controller’s definition/functionality in the script.2. we ’ll use Angular’s ngRepeat directive. . to repeatedly loop over each person. ←min.hobby}}</td > </tr > We ’ve analyzed our view page. in order to display each person in the corresponding table’s column. too: we want to divide each person’s data. {"name": "George". "hobby": "Football"}. inside a table row: <tr > <th>Name</th > <th>Hobby</th > </tr > At this point.AngularJS Programming Cookbook 23 / 31 <script src="http://ajax.com/ajax/libs/angularjs/1. which instantiates a template once per item from a collection.2.controller(’HobbyCtrl’.googleapis. "hobby": "Fishing"}. {"name": "John". here’s its final structure: script. into name and hobby.min.name}}</td > <td>{{person.js angular.hobby}}</td > </tr > </table > </body > </html> We here defined an Angular app (line 1).module(’tableApp’. using the person variable: <tr ng-repeat="person in persons" > <td>{{person. In order to meet the fore-mentioned requirements.js file.js"></script> </head> <body ng-controller="HobbyCtrl" > <table > <tr> <th>Name</th > <th>Hobby</th > </tr > <tr ng-repeat="person in persons" > <td>{{person. function ($scope){ $scope. so after a small introduction to the controller. "hobby": "Snooker"} ]. as we obviously don’t want to exercise our HTML typing. we can access the person that is processed each time. In our case.persons = [ {"name": "Thodoris". }). in the name of tableApp and attached a controller to it (line 9).name}}</td > <td>{{person. "hobby": "Basketball"}.26/angular-route. {"name": "Nick". 1: App demo 6.4 Download Download You can download the full source code of this example here: angularjs_table.AngularJS Programming Cookbook 6.3 24 / 31 Demo Here’s a quick demo of the app: Figure 6.zip . we use the <img> tag to insert an image to our site. that we can similarly refer to an image. we ’ll use the ngSrc directive in conjuction with a JSON file. assuming that we have to display some countries data in our page. within an HTML src attribute doesn’t work well. by using one of the standard Angular.js application.png" alt="A sample image" height="64" width="64"> Now. we ll make use of an existing example concept. until Angular replaces the expression inside {{hash}}.js and image insertion. everyone would go for the "markup" one. 7. is by using the ngSrc directive: <img ng-src="http://www. That is. this could be a sample image insertion: <img src="image.js JSON Fetching. For example.js templates. but I ’ll cover that usage. with which.com/avatar/{{hash}}" alt="Sample avatar" /> 7. The fore-mentioned "buggy" way to implement is. the one where I demonstrated the Angular. However.AngularJS Programming Cookbook 25 / 31 Chapter 7 AngularJS ng-src Hi there! Today we ’re gonna see how to include images in our Angular applications. too. seems like: <img src="http://www. describes in depth how to load and "consume" a json file.com/avatar/{{hash}}" alt="Sample avatar"/> But the correct way to write it. so I’ll quickly get into this. Angular’s ngSrc directive solves this problem. according to JSON fetching. we can use the double curly brace notation {{ }} to bind expressions to elements. in terms of Angular.1 Introduction In plain HTML.gravatar. using Angular markup like {{hash}} in the fore-mentioned form. I suppose. This is not so close to the introduction section.3 The Example My previously linked example. into an Angular. . one could easily claim.gravatar. too. 7. So. we may also want to let the user view the country’s flag. as the browser will fetch from the URL with the literal text {{hash}}.2 Example’s concept For our convenience. please consult this post.AngularJS Programming Cookbook 7. "flagURL": "//upload.3.success(function(data) { $scope. Practically. compared to Angular. using the ngSrc directive: index.3. "population": 11000000. To do so. 7. }).min. it includes one additional key.2 Fetching the JSON file We can load a JSON file to an Angular app into the $scope variable.org/wikipedia/en/a/ae/Flag_of_the_United_Kingdom. "population": 312247000.bootstrapcdn. $http. "flagURL": "//upload.json [ { "name": "Greece".3.js Example</title> <link rel="stylesheet" href="https://maxcdn. "flagURL": "//upload. by calling the $http service. "population": 62348447. { "name": "United States of America". rather than executing it in a browser.3 Displaying the JSON file Keeping a similar concept as in the Angular.js JSON Fetching Example let’s see how to display the country’s flag. this means that you have to deploy your app in a web server.com/bootstrap/3.css"> .svg" }.svg" }.wikimedia.wikimedia. { "name": "United Kingdom".json’).json and is placed in app’s root folder.org/wikipedia/commons/5/5c/Flag_of_Greece.countries = data.wikimedia.svg" } ] That is. 7. • Our JSON file is named as countries. assuming that: • The Angular app is named as contryApp. a core Angular service that facilitates communication with the remote HTTP servers via browser’s XMLHttpRequest or via JSONP.get(’countries.4/css/ ←bootstrap. For further details about this fact. we ’ll reuse the following code snippet from the existing example (JSON fetching).3. • Our controller is named as CountryCtrl.1 26 / 31 The JSON file Here’s a minified version of our JSON file: countries.js JSON Fetching’s one: the flagURL.org/wikipedia/en/a/a4/Flag_of_the_United_States.html <html ng-app="countryApp"> <head> <meta charset="utf-8"> <title>Angular. }).json’). }). which instantiates a template once per item from a collection. it’s easier to understand that lines 26-30 parse each country’s name. Let’s use an HTML table to group the JSON’s data properly. we ’ll use the ngRepeat directive.countries = data. we want to divide each country’s data. </script> </head> <body ng-controller="CountryCtrl" > <div class="container" > <h2>Angular. For this purpose.js"></script ←> <script> var countryApp = angular.js ng-src Example</h2 > <table class="table table-striped" > <tr > <th>Country</th > <th>Population</th > <th>Flag</th > </tr > <tr ng-repeat="country in countries" > <td>{{country. now that the country processed each time can be accessed from the country variable.com/ajax/libs/angular. function ($scope. []). So.4 Demo Let’s run it in a local server. _ For this example. Each template instance gets its own scope.population}}</td > <td > <img ng-src="{{country. $http){ $http. where the given loop variable is set to the current location item. and $index is set to the item index or key. When it comes to our case. population and flag.get(’countries. 7.cloudflare. the app can be accessed from a browser in following url:_ http://localh ost:8080/angularjs_ngsrc/ .AngularJS Programming Cookbook 27 / 31 <script src="//cdnjs. it accepts any string which can contain {{ }} markup. in order to display each one in the corresponding table’s column. That is. Lines 21-23 define the table’s headers for the country name.flagURL}}" width="100" > </td > </tr > </table > </div > </body > </html> Lines 1.controller(’CountryCtrl’. states that the directive can accept any argument of type template. In addition to what is mentioned in the Introduction section of this example. in order to repeatedly loop over each country. 7-14 and 16.min. That is. population and flag to the corresponding table column. into name. population and flag.module(’countryApp’.0/angular.name}}</td > <td>{{country. countryApp.success(function(data) { $scope. the official documentation for the ngSrc. we have to assume that each country is a table row.js/1.4. fulfill the assumptions made in JSON fetching section. zip .AngularJS Programming Cookbook 28 / 31 Figure 7.1: App screenshot 7.5 Download Download You can download the full source code of this example here: angularjs_ngsrc. please take a look over the MVC pattern). depending on the user’s input. while the second matches the last name and a greeting message. the view reflects the change. 8.1.1. please refer to the official documentation.1 Introduction 8. according to angular applications. • Filter . These are the types of Angular elements and attributes you can use: • Directive .AngularJS Programming Cookbook 29 / 31 Chapter 8 AngularJS Data Binding Hey! Today we ’ll see how we can easily update our angular views. data-binding is the automatic synchronization of data between the model and view components (for those that didn’t get this at all. Regarding Angular’s implementation. there are two text fields. Especially.An attribute or element that augments an existing DOM element or represents a reusable DOM component.1. and vice versa. 8.2. please refer to the official documentation. To begin with. For the purpose either of a getting a better understanding of the fore-mentioned or the data-binding comparison between classical template systems and Angular’s. one that matches a user’s first name. • Markup . . using ngModel. • Form controls .1 The concept Today’s concept will demonstrate the implementation of data-binding by displaying the user’s input into the View. Angular combines the template with information from the model and controller to render the dynamic view that a user sees in the browser. according to the Model. templates are written with HTML that contains Angular-specific elements and attributes. the view is a projection of the model at all times.2 What you need to know 8.Formats data for display.The double curly brace notation {{ }} to bind expressions to elements is built-in Angular markup. When the model changes. according to angular templating.Validates user input.1 Templates In Angular. For further details. ngModel has several responsibilities (you can read all of them in the official documentation. That is. the important one is the responsibility for binding the view into the model. we obviously have to define that this is about an angular application (line 2).com/ajax/libs/angular. provides data-binding. just to understand why you should deploy this app in a local server rather than just executing it in a browser.js Data Binding Example</h2 > <table > <tr > <td>First name:</td > <td><input ng-model="firstName" type="text"/></td > </tr > <tr > <td>Last name:</td > <td><input ng-model="lastName" type="text"/></td > </tr > </table > <br/ > Hello {{firstName}} {{lastName}} </body > </html> First of all.cloudflare. we display our message in line 21. textarea (or custom form control) to a property on the scope using NgModelController. HTML’s input tag. binding data to our view. we build our table view. which other directives such as input. but for the purpose of this example. Secondly. and validation 8. each one with two columns (the corresponding text field for first and last name). before diving into the source code of this example. textarea or select require. The whole process is based on the assignable variables to the ng-model. please take a look at this post.15/angular.3.js Data Binding Example</title> <script src="//cdnjs.js"></ ←script> </head> <body > <h2>Angular.2. input state control. This kind of data can be accessed/displayed using the curly brackets angular templating markup.1.js/1.2 30 / 31 ngModel The ngModel directive binds an input. This means that if the property doesn’t already exist on this scope. when used together with ng-model. 8.html <!DOCTYPE html> <html ng-app> <head> <meta charset="utf-8"> <title>Angular. which is created and exposed by this directive. as well). this works as a nested angular controller.2 The Example One file is enough! index.select. it will be created implicitly and added to the scope. Generally.min. according to our needs: two rows (first and last name).3 Demo Firstly. What is important to know. Finally. is that ngModel will try to bind to the property given by evaluating the expression on the current scope. Access the web app from your local server: .AngularJS Programming Cookbook 8. zip .2: Inserting sample data Hooray.AngularJS Programming Cookbook 31 / 31 Figure 8. let’s insert some values: Figure 8.4 Download Download You can download the full source code of this example here: angularjs_data_binding. it’s giving feedback! 8.1: Application’s initial state Now.