© V. Keerti Kotaru 2016

V. Keerti Kotaru, Material Design implementation with AngularJS, 10.1007/978-1-4842-2190-7_2

2. Getting Started

V. Keerti Kotaru

(1)Hyderabad, Andhra Pradesh, India

This chapter discusses multiple options for getting started with a project based on Angular Material. Along with referencing Angular Material and AngularJS JavaScript libraries, the chapter will elaborate on development environment setup, package manager options, and so on. In addition, the chapter will focus on setting up the environment for ES5 as well as ES2015 (ES6). The approaches described in the chapter should help a medium or large project setup.

Scripts

The following scripts are required for running an Angular Material application :

  1. AngularJS: Primary dependency, AngularJS framework library.

  2. Angular Animate: AngularJS animations library.

  3. Angular ARIA: ARIA (Accessible Rich Internet Applications) provide state and semantic information for tools used by persons with disabilities. ngAria in AngularJS provides out-of-the-box support and improves default accessibility of the application.

Angular Material scripts:

  1. 4. Stylesheet: the angular-material.css provides CSS classes and styles for Angular Material.

  2. 5. Angular Material library.

Optional dependencies :

  1. 6. Angular Messages is for showing messages and errors within the HTML templates. It includes the module ngMessages. Typically, the module is used while performing client-side validations for a form. Include this library when directives and other artifacts that are part of the ngMessages module are used in the application.

  2. 7. Angular Sanitize is to sanitize HTML by escaping tags keyed into input elements (or by other means). The library includes the module ngSanitize. Include the library when the service, provider, or filter that is part of the ngSanitize module is used. Not a mandatory dependency.

Code Editor /Integrated Development Environment (IDE)

All the concepts discussed in this book are implemented using JavaScript, HTML, and CSS. To get started, we can even code in a simple code editor like Notepad. However, a good code editor helps with better code formatting, editing features, autocomplete function signatures and elements, debugging aspects, and so on.

The following are recommended to use. They are easy to install, free for non-commercial use, and installable on both Windows and Mac.

  1. Sublime Text

  2. Visual Studio Code

  3. Atom

  4. Chrome Dev Editor

Get Started with Angular Material

Use this section to set up a sample code repository for trying out Angular Material samples on your machine. Practice various code samples demonstrated during course of this book.

To get started, create an empty directory and open it in a code editor of your choice. Create a new file and name it index.html. Next, run through the following steps.

  1. Code “Hello World—Angular Material.”

  2. Set up a developer class web server and run the sample.

Let us look into each step in detail.

Step 1: Code “Hello World —Angular Material”

Let us get started by referencing all needed libraries for an Angular Material application. The easiest way to reference needed JavaScript libraries is by using a CDN (Content Delivery Network) URL. Refer to the preceding “Scripts” section for a list of required libraries.

Copy-paste the following code in the index.html we just created.

 <!DOCTYPE html>
<html>
<head>


    <!-- Reference Angular Material stylesheet -->
    <link rel="stylesheet" href="https://cdn.gitcdn.link/cdn/angular/bower-material/v1.0.8/angular-material.css">
        <title>Hello World</title>
</head>


<body ng-app="sampleApp" layout="column">

    <!-- Bootstrap Angular Material Application. We create a module with ngMaterial as a dependency. Learn more about an AngularJS module in a later section of the chapter -->
    <script>
        angular.module("sampleApp", ["ngMaterial"]);
    </script>


    <!-- Create a title: Here we are creating a simple toolbar. We will get into details of various controls in Angular Material during course of this book. For the moment, understand that it is an Angular Material element for creating a title and a toolbar-->
    <md-toolbar layout-padding>
        <div class="md-toolbar-tools">
            <h2>Welcome to Angular Material</h2>            
        </div>
    </md-toolbar>


    
    <!-- Reference needed scripts. See scripts section above for details on each script-->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script> <!—Angular Messages is optional for this sample -->
    <script src="https://cdn.gitcdn.link/cdn/angular/bower-material/v1.0.8/angular-material.js"></script>
</body>
</html>

At the time of writing this book, version 1.5.6 for the first four scripts and 1.0.9 for Angular Material were the most recent. Look for a newer version while trying your samples and preferably use the latest version.

Step 2: Set up a developer class web server and run the sample

We need to run samples on a local web server . As a developer running samples on a laptop/desktop, we do not need the high-end features of a web server. The following are easy to install and lightweight options. You may choose to follow these instructions and set up on a developer machine, or you can run very well an existing web server that you are comfortable with.

Option A: Live Server

Live server autorefreshes the browser window as we make changes to the files in the editor. Often, by the time we switch to the browser for results, will see the window updated with the latest code.

Prerequisite: Make sure Node Package Manager (NPM) is already installed on the machine. Refer to Setup Node Package Manager Section, later in the chapter for details.

Install: Live Server is available as an NPM package. Install by using the following command.

npm install -g live-server

Note that -g option installs the package globally on the machine. It allows using the package from any directory without performing another local install.

On a Mac or Linux machine, you might need sudo access to install the package globally. Consider running the command as follows:

sudo npm install -g live-server

On a Windows machine, run command prompt as administrator.

Run the app

Open terminal (or command prompt) and CD (change directory) into the newly created directory with index.html.

Next run the following at the prompt.

live-server

This should run the live server on current directly and open the default browser with index.html loaded. See Figure 2-1 for the result.

A416608_1_En_2_Fig1_HTML.jpg
Figure 2-1. Rendered output for “Hello World—Angular Material”

At this point we are all set. We can use this setup to code more samples demonstrated during the course of this book and run them.

Furthermore, notice that it defaults to port 8080. To see all available options with live server, run

live-server -h

Option B: Serve

If you are uncomfortable with live reload of web pages, consider using serve. Effectively, it is similar to live server without the live reload option.

Prerequisite: Make sure NPM is already installed on the machine. Refer to Setup Node Package Manager Section, later in the chapter for details.

Install: Serve is available as an NPM package. Install by using the following command.

npm install -g serve

Note that the -g option installs the package globally on the machine. It allows using the package from any directory without performing another local install.

On a Mac or Linux machine, you might need sudo access to install the package globally. Consider running the command as follows:

sudo npm install -g serve

On a Windows machine, run command prompt as an administrator.

Run the app

Open terminal (or command prompt) and CD into the newly created directory with index.html.

Next run the following at the prompt.

                      serve                                                                                                                                                          

This should serve current directly and its files on an HTTP URL for browsers. Notice that it defaults to port number 3000. Open the browser of your choice and run localhost:3000. See Figure 2-1 for the result.

At this point we are all set. We can use this setup to code more samples demonstrated during the course of this book and run them.

Furthermore, to see all available options with serve, run

serve -h

Option C: IIS Express

If you are on a Windows machine, you might consider this option. Download and install the latest version of IIS Express from Microsoft’s download page: www.microsoft.com/en-us/download . Run through the setup wizard to install IIS Express.

Typically, IIS Express will be installed on “C:Program FilesIIS Express” or “C:Program Files (x86)IIS Express.”

Run the app

Run the following command:

C:IIS-installed-locationiisexpress /path:C:your-sample-folder /port:3001

3001 is a sample port number. Run on any available port number.

Files in your sample folder now can be accessed over an HTTP URL. Open the browser of your choice and run http://localhost:3001. See Figure 2-1 for the result.

At this point we are all set. We can use this setup to code more samples demonstrated during the course of this book and run them.

For more information on IIS Express run,

C:IIS-installed-locationiisexpress /help

Working with Code Samples

All code samples developed for this book are available at this GitHub URL: https://github.com/kvkirthy/Angular-Material-Samples . Clone or download the repository.

Run Samples

Use a web server of your choice. There are three options—live server, serve, and IIS express—described in the preceding section. Run the web server at root level. As we open samples in a browser, will see a layout depicted in Figure 2-2.

A416608_1_En_2_Fig2_HTML.jpg
Figure 2-2. Code samples

On the left, in the navbar, notice a complete list of chapters. Links to individual samples are on the right. Click the link; the sample opens in a new window.

Folder Structure

Open the downloaded samples’ code repository in an IDE of your choice.

The code samples follow a simple directory structure. You will see a directory for each chapter. Browse through code samples for each chapter, under its folder. See Figure 2-3.

A416608_1_En_2_Fig3_HTML.jpg
Figure 2-3. Code samples folder structure

For many samples, within the chapter, a folder named “app” has JavaScript code (modules, controllers, etc.).

All the libraries are included in the bower_components folder at the root level.

AngularJS Basics

This section describes AngularJS basics . It is intended to provide context for understanding Angular Material. If you are familiar with AngularJS, you should be good to skip this section and move on to the next section.

As mentioned earlier, AngularJS is an MVW framework. That is, Model-View-Whatever. Effectively we can use AngularJS to implement Model-View-Controller or Model-View-View-Model patterns. In either case a model (or view model) is in the browser. It is a JSON object, which could be bound to a view or an HTML template. A property in the model JSON object could be bound to a control like text field, drop-down, radio button, and so on.

Data Binding

AngularJS supports two-way data binding. A change made to the model is updated in the view. If view makes changes, they are updated in the model.

Consider the following sample. It has a text field and a label. A model object aModelObject is bound with a text field and a label in “strong” HTML element. Curly braces are used for writing the value of an object or an expression directly in HTML. Using a directive ng-init, we initialize the variable aModelObject with an initial value. We use another directive ng-model for binding a value with an HTML element, in this case an input tag.

<div ng-app>
<span ng-init="aModelObject='Initial Value'"></span>
 <input type="text" ng-model="aModelObject">
 <div>  
   <strong>{{aModelObject}}</strong>
 </div>
</div>

Initially, the text field and the label show “Initial Value” as they are bound to the model object (aModelObject). See Figure 2-4.

A416608_1_En_2_Fig4_HTML.jpg
Figure 2-4. Initial value as the controller loads

As we change value in the text field (change triggered in the UI), the model object is updated. And hence, the label shows the new value. See Figure 2-5.

A416608_1_En_2_Fig5_HTML.jpg
Figure 2-5. As user edits the field, the label is udpated

Directive

AngularJS directives allow creating custom HTML elements, attributes, comments, and CSS classes. In the preceding example, we used three built-in directives.

  1. ng-app: Used for initializing the AngularJS application.

  2. ng-init: Used for initializing a variable or model object.

  3. ng-model: Used for binding model and view.

There are many built-in directives, and we can create custom directives specific to an application. Explore more about directives at docs.angularjs.org/guide/directive.

Note

All built-in directives are prefixed with ng-.

AngularJS Module

Logical units in AngularJS app could be grouped together to create a module. Every application bootstraps with one module. All other modules would be its dependencies or dependencies of dependencies.

Create a module using the following application programming interface (API).

var myModule = angular.module("sampleApp",["module1", "module2"]);

Find out more about modules at https://docs.angularjs.org/guide/module .

DI

DI helps with loose coupling among code units, functions, and objects. AngularJS uses DI quite effectively. The following are some of the code artifacts we could create in AngularJS:

  1. Service

  2. Factory

  3. Provider

  4. Value

  5. Constant

  6. Controller

  7. Filter

In an example, a service could be injected in a controller or another service or a factory. During this process, AnguarJS ensures that a given object is ready for use and that API or functions on the object may be invoked. For example, every controller needs $scope object injected. Variables and objects on $scope are accessible in the HTML view.

Controller

It binds view (HTML template) and model objects created in JavaScript together. In the earlier example, we initialized and used a model variable in HTML. It might work for simple flags. However, for complex data representations, which could also be obtained from a server-side API, we need to use JavaScript code.

A controller could be a JavaScript function. Create a controller using the following API.

myModule.controller("firstController", function($scope){
                $scope.title = "Select a City";
                $scope.cities = ["San Francisco", "New York", "Bengaluru", "Mumbai", "Hyderabad"];
            });

Here the first parameter is used as name of the controller. The controller definition is the second parameter, a callback function. This function has been injected with a scope object, $scope.

Scope ($scope) provides context and is used to hold model objects. A JavaScript variable or an object could be set on scope. It will be available to use on view or HTML template. In this example, title could be used in associated HTML template.

Find out more about controllers at https://docs.angularjs.org/guide/controller .

View / HTML template

HTML templates (markup) renders the view or the UI. The user interacts with the elements in the view. We use various AngularJS directives and filters for providing additional power and functionality to HTML.

Consider the following code and explanation of the HTML template.

<div ng-app="sampleApp">
    <div ng-controller="firstController">
        <h2>{{title}}</h2>
          <select name="dpCities" id="dpCities" ng-model="selectedCity" ng-options="city for city in cities"></select>
    </div>
</div>
  1. As for the earlier sample, use ng-app to bootstrap Angular. Here we specify the module name. Hence, it is the main or root module. All other modules are dependencies of this module or dependencies of dependencies.

  2. Use a directive ng-controller and set the context of controller within a div tag.

  3. The title is shown as an h2 element. “title” is a variable on scope bound on the UI as a label.

  4. Notice the select element with ng-options directive. The controller’s scope has list of cities. It is being set to the drop-down using the ng-options directive. The selected value will bind to a variable selectedCity.

Services

Services are reusable code artifacts in AngularJS. They are singleton objects and maintain state once the application bootstraps.

In an example, code to make HTTP API calls is encapsulated in a built-in service called $http.

Note

All built-in services in AngularJS are prefixed with $

We can create our own services using the following API. Consider the following code.

myModule.service("sampleService", function(){
  // sample service definition.
});

The service() API creates a new service. The first parameter is the service name. The second parameter is a callback function with definition of the service.

The “sampleService” could be used anywhere in the module (and in other modules with the current module as a dependency).

Provider

A provider is very similar to service. In fact, a service is a type of provider. We create a provider in a special case, which is a function or JSON object required while bootstrapping the module.

AngularJS module has an API “config,” which accepts a callback function. It is invoked only once, while bootstrapping the application (as the browser loads the app).

A provider is a specialized object which could be injected/used in a config function. A provider is expected to have a $get function. When a provider is injected/used in another service or a controller, only the code in $get is exposed. The $get function is a factory. It is expected to return an object (or a function) that could be used in a service.

However, while it is used in a config function, API (functions) and fields on “this” object could be used.

Consider the following sample. It defines a provider with a function on this object and $get factory function.

myModule.provider("aSample", function(){
    this.aProviderFunction = function(){ // This could be invoked directly in a config function
             return "Provider Function";
         };
         this.$get = function(){ // This is used in a factory, service, or controller.
             console.log("$get invoked. A factory function");
             return this.aProviderFunction;
         };
});

When the provider is injected into a controller, $get is invoked. In the current sample, it prints “$get invoked. A factory function.”

As mentioned earlier, the $get function acts as a factory. It returns a function for use in the controller.

// Provider injected in the controller.myModule.controller("sampleController", function($scope, aSample){
                console.log(aSample()); // use the function returned by $get
            })

When it is injected into config function, whole provider object and its API are accessible. Consider the following code. As we call aProviderFunction(), it prints the returned string, “Provider Function” on console.

myModule.config(function(aSampleProvider){
    console.log(aSampleProvider.aProviderFunction());
});

Learn more about providers here: https://docs.angularjs.org/guide/providers .

Making the Code Minification Safe

Unlike function parameters, objects may be injected in any order. The object is identified by its name. When the JS is minified, the variables are renamed and DI no longer works. The following syntax solves this problem. It injects an object using its name as a string.

Here is the syntax we used earlier.

myModule.controller("firstController", function($scope, aSample){
        // Controller definition
});

To make it minification safe, use the following array syntax.

myModule.controller("firstController", ["$scope","aSample",function(scope, sample){
        // Controller definition
});

Notice parameters on the function that are named scope and sample. They could be named anything now. DI uses string values provided before the function. As the string values are untouched during DI, it is minification safe. DI will not break with minified code as well.

Learn more about DI here: https://docs.angularjs.org/guide/di .

Pakage Managers and JavaScript Modules

Setup Node Package Manager - NPM

NPM is a popular package manager. Many open source developer tools, JavaScript libraries, and frameworks are available as NPM packages. Hence, it has become a one-stop source for downloading such packages.

A package manager downloads and installs a given package and all of its dependencies at once. As a consumer of the package, we do not need to keep track of dependencies or separately download or install them.

NPM is part of a larger NodeJS offering. Download the node installer from nodejs.org. For the purposes of this book, we will primarily be using NPM.

You can install a package by running the following command:

npm install <package name>

It downloads the package (and its dependencies) to node_modules folder in the current directory. As an option, -g helps install a package globally on the machine. Use this option to install packages that are environment specific and are not directly related to the code base; for example, task runners, tools, web servers, and so on. This helps make project folder self-contained and not polluted with things beyond the application.

Often, we need elevated access to run the npm install with -g option. Hence use sudo on a Mac or Linux machine (that is sudo npm install -g <package name>). On a Windows machine, run command prompt as administrator.

The preceding section “Get Started with Angular Material” explains the easiest implementation for referencing required JavaScript libraries and writing the JavaScript code. The following are more sophisticated and effectively help to set up a medium- to large-scale JavaScript project.

Download Angular Material using NPM

Angular Material is available as an NPM package. To get started with NPM, create a new directory and open a command prompt or terminal at this directory. Install Angular Material with the following commands:

npm install angular-material

It downloads Angular Material and its dependencies to node_modules directory.
Note

Creating an NPM package for the sample will help maintain repository and dependencies in one place. This may not be a necessity for the unsophisticated sample we are working on. However, this process saves time and energy for a big and complex code repository.

npm init
(Initializes an NPM package)


npm install angular-material –save
(Saves Angular Material as dependency of current project in package.json, so that next time just running npm install downloads all given packages)

Reference scripts

Create an index.html in the newly created directory (at the level of node_modules). Reference the downloaded scripts. References could be script tags (and link tags) in index.html or any module loader like RequireJS (Asynchronous Module Definition - AMD implementation), CommonJS, and so on.

Let us use the simplistic approach and include scripts in index.html

<link rel="stylesheet" type="text/css" href="node_modules/angular-material/angular-material.min.css">

<script type="text/javascript" src="node_modules/angular/angular.min.js"></script>

<script type="text/javascript" src="node_modules/angular-animate/angular-animate.min.js"></script>

<script type="text/javascript" src="node_modules/angular-aria/angular-aria.min.js"></script>


<script type="text/javascript" src="node_modules/angular-material/angular-material.min.js"></script>

Download Angular Material using Bower

Bower is a popular package manager for front-end artifacts. It is optimized for front-end libraries and scripts. It is lightweight due to its flat dependency tree. While using ES5 (current JavaScript version at the time of writing this book), bower is a good package manager to use for front-end libraries.

Install bower globally on your machine with NPM. This is a one-time activity. Subsequently, as we download more packages using bower on the same machine, running this step will not be required again.

npm install -g bower

To avoid running into access issues, consider running the preceding command with sudo (that is, sudo npm install -g bower) on a Mac or Linux machine. Run the command prompt as administrator on a Windows machine.

Then use bower to download Angular Material.

bower install angular-material

It downloads the entire Angular Material library and all of its dependencies under bower_components folder. See Figure 2-6.

A416608_1_En_2_Fig6_HTML.jpg
Figure 2-6. Angular Material and its dependencies downloaded with bower
Note

Creating a bower package for the sample will help maintain repository and dependencies at one place. This may not be a necessity for the unsophisticated sample we are working on. However, this process is a must and saves time and energy for a big, complex code repository.

bower init                                                                   
(Initializes a bower package)


bower install angular-material –save
(Saves Angular Material as dependency of current project in bower.json, so that next time just running bower install downloads all needed packages)

Reference scripts

Create an index.html at root folder of the project. Reference the downloaded scripts in bower_components. References could be script tags (and link tags) in index.html or any module loader like RequireJS (AMD implementation), CommonJS, and so on.

Let us begin with the simplistic approach and include scripts in index.html.

<link rel="stylesheet" type="text/css" href="bower_components/angular-material/angular-material.min.css">

<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>

<script type="text/javascript" src="bower_components/angular-animate/angular-animate.min.js"></script>

<script type="text/javascript" src="bower_components/angular-aria/angular-aria.min.js"></script>

<script type="text/javascript" src="bower_components/angular-material/angular-material.min.js"></script>

SystemJS & JSPM (JavaScript Package Manager )

SystemJS is a good module loader until browsers support the ES2015 way of importing them. This is one step in the right direction. As browsers start supporting new format, SystemJS gets out of the way easily. SystemJS understands existing JavaScript module loaders like RequireJS or CommonJS and of course the ES6 module loader.

JSPM is a package manager for SystemJS-based system. It is a node package . Install it with the following command.

npm install jspm -g                                                          
Note

This is a one-time command that installs JSPM globally on the machine (with -g option). For future package installations, this step need not run again.

However, JSPM could install locally to the project. Replace -g option with --save-dev option to save it as a Dev dependency of the project’s package.

To install Angular Material and dependencies , use the following command.

jspm install angular-material
Note

We could configure to use Babel, Traceur, or TypeScript transpilers. While setting up the package for the first time, JSPM will prompt to choose a transpiler.

Install CSS plug-in for loading CSS files .

jspm install css                          

Code “Hello World —Angular Material”

Add references to SystemJS and its configuration. JSPM install command downloads packages to jspm_packages folder. It downloads SystemJS as well, which supports multiple module formats and allows loading them.

<script src="./jspm_packages/system.js" type="text/javascript"></script>
<script src="./config.js" type="text/javascript"></script>

The following script in Index.html will load main file (root)—main.js in app folder. Every other file that loads is a dependency of this file or dependencies of its dependencies.

Import function loads main file and its dependencies asynchronously. It returns a promise, which is resolved once all files load.

<script type="text/javascript">
        System
        .import('app/main')
        .then(() => console.log("Angular Material Sample loaded successfully"))
</script>
Note

The then function called on resolving the promise uses arrow function syntax of ES2015.

Config file has reference paths to modules and script files :

"angular": "jspm_packages/github/angular/[email protected]",
"angular-animate": "jspm_packages/github/angular/[email protected]",
"angular-aria": "jspm_packages/github/angular/[email protected]",
"angular-material": "jspm_packages/github/angular/[email protected]",

Import these scripts in main.js. Here we are using ES6 syntax. It is transpiled to ES5 format by Babel or Traceur.

import 'angular';
import 'angular-animate';
import 'angular-aria';
import 'angular-material';

Controller : export the function and register it with AngularJS as a controller. Similar to the previous example, it has a single data element on $scope, message.

controller.js
export default function($scope){
     $scope.message = "Hello World";
};

export default” is ES2015 syntax for modules. The given function is exported and available for all that import the current module.

Consider main.js or root file that acts as starting point to the application in JavaScript.

main.js
import 'github:angular/[email protected]/angular-material.min.css!';
import 'angular';
import 'angular-animate';
import 'angular-aria';
import 'angular-material';
import controller from './controllers';


angular.module('es6Sample', ['ngMaterial'])
.controller('firstController', controller);

This file imports all of its dependencies. Each dependency might have more dependencies .

As for the ES5 sample, create a new Angular module, es6Sample. Add ngMaterial dependency for Angular Material services and directives. Import controller function from controllers.js and register with the module.

Note

Angular Material CSS file loads with the help of CSS plug-in.

Limit Scope Using Closure

Consider the following coding practice . If you are not using any module loader in JavaScript, this is a good alternative. For the purposes of this book, it is only for reference. The code sample in the “Bower” section of Chapter 2 uses this approach.

The start point for the app is main.js, and controller.js has the first sample controller. Consider code for the following two files. In this sample, a coding style that helps to avoid creating global variables and objects is shown. A global variable could be accessed across the application, causing unforeseen behavior and hence resulting in bugs. We limit the scope by writing code in a self-executing function: self-executing because code needs to run as soon as script loads. All variables declared in it have local scope, accessible only within the function.

main.js
// ngMaterialSample is an Angular module used across the application. Hence it is intentionally a global variable.
var ngMaterialSample = (function(angularRef){
        'use strict';
        return angularRef.module('ngMaterialSample', ['ngMaterial']);
})(angular);

Here, angular (comes from angular.min.js script) is passed-in as a parameter. We create a new Angular module ngMaterialSample. It has dependency on ngMaterial. This will enable using Angular Material directives and services in the application.

controller.js
(function(app){
        'use strict';


        app.controller("sampleController", function($scope){
                $scope.title = "Welcome to Angular Material";
        });


})(ngMaterialSample); // ngMaterialSample is the module object to use for creating a controller.

In controller.js (it should load after main.js), pass-in ngMaterialSample global object as a parameter. We create a controller in module/self-executing function. Controller has one data element, title on Scope.

Include the following scripts in index.html

<script type="text/javascript" src="app/main.js"></script>
<script type="text/javascript" src="app/controller.js"></script>
Index.html - template to show title:
<body ng-app="ngMaterialSample">
        <div ng-controller="sampleController" >
                <md-toolbar>
                        <h2>{{title}}</h2>
                </md-toolbar>
        </div>
</body>

ng-app is set on body tag. The ngMaterialSample module bootstraps here. Controllers (and other artifacts) of this module could be used on any child elements of body tag. The sampleController is scoped to div element.

md-toolbar is an element/directive in ngMaterial module. ngMaterial is referenced as a dependent module for ngMaterialSample. The directive helps render Material Design–style toolbar on the page.

Note

In AngularJS, a directive helps create custom DOM elements, attributes, CSS classes, or comments. More often, with directives we can provide custom functionality to HTML elements or attributes. There are many directives available out of the box with the framework. We can create our own custom directives as well.

Notes on ES2015 (Also Called ES6 )

Everyone in the JavaScript world is excited about ES2015 . It has great language features, inbuilt module support, classes, arrow functions, better variable scope management, and so on.

However, we are not fully there yet (at least at the time of writing this book). Browser support is growing, but it will be a while before all current browsers run ES2015 out of the box.

To start using ES2015 features on unsupported browsers, we could use transpilers like Traceur, Babel, or TypeScript.

Angular Material features demonstrated in this book are based on Angular 1.x version. It is still based on ES5 JavaScript. Angular2 can fully take advantage of ES2015 (ES6). Having said that, we can code in ES2015 today. Use transpilers and convert it to ES5 so that browsers can run the code.

Summary

This chapter aims to provide various options to get started with Angular Material. It not only focuses on ways to reference Angular Material and its dependencies in the project but also helps set up the project. It aims to look beyond samples demonstrated.

At the time of writing this book (2016), a JavaScript project should brace itself for migrating to ES2015 (ES6). The language features in the newer version of JavaScript are too good to ignore. With such migration in the context, SystemJS and JSPM fit the bill. Create your Angular Material project with SystemJS and JSPM the approach described in the chapter. SystemJS supports multiple module formats. AMD (RequireJS) and Node-style CommonJS are today’s famous module systems. ES2015 has come up with new syntax and features for module loading. SystemJS supports these module formats.

If you are planning on a small-scale Angular Material project, it is possible that such a setup could be overwhelming. Get started with Google CDN or the bower approach. It is easy to begin and saves time up front.

References

For live server NPM package, see https://www.npmjs.com/package/live-server

For Serve NPM package, see https://www.npmjs.com/package/serve

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.163.62