Responsive Web Design with AngularJS

By Sandeep Kumar Patel
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies

About this book

AngularJS is an open source JavaScript framework, built to create dynamic web applications using HTML, JavaScript, and CSS. AngularJS has many advanced features that can be used to leverage responsive application development.

Responsive Web Design with AngularJS follows a detailed step-by-step approach to explain each key concept, with sufficient code and examples. This book will teach you how to implement dynamic routing, responsive custom directives, and breakpoints for your web page, followed by a section on debugging and testing.

By the end of the book, you will be able to develop and design exciting single page applications with AngularJS and make the applications responsive on different devices. With ample screenshots and code offering you a detailed insight, this book will ensure your success in developing responsive applications.

Publication date:
December 2014
Publisher
Packt
Pages
128
ISBN
9781784398422

 

Chapter 1. Introduction to Responsive Single Page Application and AngularJS

In this chapter, you will learn about the need for responsive web design, explore the building blocks of a single page application. At the end, we will discuss some features of the AngularJS library with a quick look at their syntax and understand their role in responsive web application development.

 

Why responsive design?


In the current age of digital revolution, there are many devices with different screen sizes. This increases an additional layer of complexity for web development. A web application now has to present a similar experience across different devices. To solve this problem, it needs a design solution .This solution is termed as responsive design. There are also some key areas in the responsive design approach. They are as follows:

  • Increase in the use of handheld devices (mobile, tablet): One example is data analytics provider, Flurry Inc. It released data about mobile application usage. The published report shows the mobile application usage is increasing. You can view this report at http://www.flurry.com.

  • A single codebase is easier to manage: From a developer's point of view, it is easier to manage a single code repository base for different devices. The developer has to make a change in one place for a change request in the functionality.

  • Better Engaging content: Based on the device, the view will be optimized through responsive web development, which increases the user's interest. Hence, the engagement of the user will remain the same as the original application.

  • Conversion rate and lead generation: Through responsive web development, an optimized view will be presented to the user which will increase engagement and thus the probability of a higher conversion rate and lead generation.

  • Better user experience: Using responsive design, we can show better content to the user that includes appropriate images and widgets. This increases the user experience for the application.

  • Page load speed: Using responsive design, only required content can be downloaded to the targeted device; hence, the page speed will increase.

 

What is single page web application?


In a single page application (SPA) architecture, the presentation logic is moved to the client side. SPA can redraw a part of the UI on a page without a complete round trip or reload of a window.

The following diagram shows the building blocks of a single page web application:

Template

Templates can be thought of as placeholders for styling and structure that will be modified by the application's code. This way the content to be displayed can be generated dynamically by the app, while the presentation remains static. In web application development, domain templating is a very well known concept and has been used by developers. In a more specific sentence, we can define a template as any document or file with a presentation format that can be created initially and does not have to be recreated for subsequent use.

Note

To know more about the latest developments in templating, visit http://www.html5rocks.com/en/tutorials/webcomponents/template.

Partial

The partial components is similar to a template that can be created once and reused many times. The only difference between partial and template is that partial is the smallest unit of a reusable chunk of code.

Router

The router components is used for correctly navigation to a view based on the request. In single page application, the routing logic is present in the client side.

Controller

The controller components is the owner of a part of a page. It provides a scope to be used by the specific part of the page. In single page application, controller is used to share objects or create common behavior in terms of event callback functions.

Real-time communication

Real-time communication introduces the two-way request-response mechanism. Technologies like WebSocket, Server-Sent Event (SSE), and WebRTC made this possible. In single page application, real-time communication is used to share the load between the server and client. Instead of polling from the client side, now push updates from the server side can now be used to sync the application.

Local storage

Local storage provides a client-based storage system to cache the data in the browser. This really helps by reducing the number of HTTP requests to the server. In single page application, the client first checks the data required by a request in the local storage and if it is not present in local, then it makes a call to the server.

 

Understanding responsive single page application


In the previous section, we explored responsive and single page applications, two modern features of a web application. In this book, we will develop an SPA with responsive design using AngularJS, which is a perfect fit for SPA development as all the characteristics of SPA are present within the library. In the next section, we will quickly go through these features.

 

What is an AngularJS framework?


AngularJS is a complete client-side solution for web application development and is maintained by Google Inc. The AngularJS framework is one of the best frameworks to create single page application. AngularJS follows declarative programming similar to an HTML element declaration. This makes AngularJS simple.

The AngularJS library is a perfect fit for SPA development. AngularJS is more like a Model View Whatever (MV*/MVW) design pattern instead of Model view Controller (MVC).This means that an AngularJS application can be developed with the model and view features.

Note

To know more about MVW, visit https://plus.google.com/+AngularJS/posts/aZNVhj355G2.

 

Exploring the features of AngularJS


In this section, we will quickly go through some of the important features provided by the AngularJS library. The goal of this section is to understand each feature with its appropriate syntax.

Some of the features that we are interested in to build responsive web applications are listed as follows:

  • The AngularJS module

  • The controller scope

  • The AngularJS routing module

  • The provider

  • Data binding

  • Angular expressions

  • Built-in directive

  • Custom directive

The AngularJS module

Using the AngularJS module feature, an independent code section can be created. A module can be easily detachable. This module helps with better code management and it helps to work in large teams. Loose coupling allows developers to create their parts of the project independently. The angular.module() method is used to create a module. The syntax to create an AngularJS module is as follows:

var aModule = angular.module("<moduleName>",
["<injectedModule1>","<injectedModule2>"]);

In the above code, the angular.module() function takes two parameters: the first is the module name and second is the array of dependent module. The parameters used to create a module are as follows:

  • moduleName: This represents the name of the module registered to AngularJS

  • injectedModule: In the above syntax, injectedModule1 and injectedModule2 are modules that are injected as input to the targeted module

Note

To learn more about the AngularJS module, visit https://docs.angularjs.org/guide/module.

The controller scope

AngularJS provides the controller scope to create a new controller to manipulate HTML DOM indirectly under its scope by modifying properties present inside its scope. AngularJS uses the controller feature to perform the following operations:

  • Setting up the scope object inside the controller

  • Modifying the value of the scope object inside the controller

The controller() method is used to create a controller section. The syntax to create a controller is as follows:

var aModule = angular.module("<moduleName>",
    ["<injectedModule1>","<injectedModule2>"]);
aModule.controller('<controllerName>',
    ['<injector1>','<injector2>',
    function(injector1,injector2) {
    //Definition of the controller
}]);

Some parameters used in the preceding syntax to create a controller section are as follows:

  • controllerName: This represents the name of the controller created using the AngularJS library

  • injector: In the above syntax, injector1 and injector2 are individual modules that are injected to be used by the controller scope

A controller scope can be defined inside HTML DOM using the ng-controller directive. The following code shows the use of the controller directive in the HTML file:

<div ng-controller="<controllerName>">
    <! -- HTML element inside the controller scope -->
</div>

Note

To learn more about the AngularJS controller, visit:

https://docs.angularjs.org/guide/controller.

The AngularJS routing module

AngularJS provides a router module to determine which HTML template or partial will load based on the request. AngularJS provides the ngRoute module with $routeProvider to route the request to the appropriate view. The following code shows the syntax to create the route to the request:

var myApplication = angular.module("<applicationName>",
    ["ngRoute"]);
myApplication.config(function($routeProvider) {
   $routeProvider.when('/viewName1', {
      templateUrl:'/partial1.html'
   });
   $routeProvider.when('/viewName2', {
      templateUrl:'/partial2.html'
   });
   $routeProvider.otherwise({redirectTo:'/viewName1'});
});

The details of the preceding code are as follows:

  • applicationName: This represents the module name of the application.

  • config(): This function configures the routing module for the incoming request.

  • viewName: This represent structure of the incoming request pattern. In the previous code, the incoming requests that are handled are viewName1 and viewName2.

  • when and otherwise: These are the associated clauses to redirect the request to the targeted HTML view.

  • templateUrl and redirectTo: templateUrl contains the address of the URL for the targeted response and redirectTo points to default route for a request.

Note

To learn more about the AngularJS router provider, visit https://docs.angularjs.org/api/ngRoute/provider/$routeProvider.

The AngularJS provider

AngularJS provider is the core feature through which you can serve an API throughout an application. Angular JS-based value, factory, services, and constants are syntactic sugar on top of core provider implementation. Let's take a look at each implementation on the core provider in the following section. A provider can be created using the provider() method and an object with a $get function that returns an instance. The angularJS provider creates only one instance of itself to be used. The syntax to create a AngularJS provider is as follows:

var myApplication = angular.module("<applicationName>",[]);
myApplication.provider("<theProviderName>", {
    //Code for the provider implementation
    $get: function() {
        return //object that will be used by the caller;
    }
});

A provider method can be injected and called inside a configuration block or module. The following code shows the use of a declared provider inside the configuration block:

var myApplication = angular.module("<applicationName>",[]);
myApplication.config(function (theProviderNameProvider) {
//code to access theProviderNameProvider
})

Data binding

AngularJS provides scope-based data binding from HTML, DOM, and JSON data. Data binding happens in two different steps: compiling and linking. In the compile phase, the HTML file is converted into a JavaScript function. In the linking phase, the real data is linked to the HTML element. Angular provides two-way binding between the view and model features by synchronizing JavaScript objects and HTML elements.

The following diagram shows the process of data binding, where template is compiled once and view is generated by linking to model. This shows the tight coupling between the model and view features where any change in either of them is in sync.

AngularJS expressions

Expressions in AngularJS are like JavaScript statements that can be evaluated at runtime. These expressions are represented by double curly braces. They involve the JavaScript value object whose exact value arrives while linking the time of model objects. The following code shows the syntax of using AngularJS expression:

{{expression}}

An example of AngularJS expressions are as follows:.

<div>
    Addition of 2 and 3 are {{2+3}}
</div>

AngularJS also provides a one-time binding of an expression. The one-time binding expression value, once set, will not change. In simple words, if a variable is being updated on every click, normal binding would cause the display to change each time the variable changes. However, in a one-time bind expression, the display will remain set to the first valid value. A one-time expression can be defined using double colon (::).The following code shows the use of one-time expression binding:

<div>
    Name of the student is {{::studentName }}
</div>

Note

One-time binding of the scope variable value was introduced in AngularJS version 1.3.

Built-in directive

AngularJS provides many built-in directives to help with web application development. These core directives are prefixed with ng-*.It should be noted that all core directives are prefixed with the ng keyword and should not be used while creating a custom directive. Some of the built-in directives present inside the AngularJS library are as follows:

  • ngApp: This represents the root element of the application.

  • ngRepeat: This directive is used to iterate an array or properties inside the object.

  • ngIf: This directive is used to evaluate conditional expression and adds or removes the element from the DOM based on its result.

  • ngClick: This directive is used to attach a custom callback for a click event.

  • ngInclude: This directive is used to fetch and compile the external HTML fragment and include it to the current document.

  • ngClass: This directive is used to manipulate CSS classes that are used for an element.

  • ngBind: This directive is used to replace the text content with the specified HTML. The ngBindHTML replaces an element's inner HTML with the specified HTML.

  • ngSubmit: This directive is used to attach a custom callback method to an onSubmit event of a form.

  • ngModel: This directive is used to attach a form element to a scope.

    Note

    To learn more about built-in directives and for the list of all core directives inside the AngularJS library, visit https://docs.angularjs.org/api/ng#directive.

Custom directive

AngularJS follows the directive-based approach for reusable component development. A custom directive is similar to an HTML element with its own definition and method to manipulate the DOM. AngularJS provides the directive() method to create a custom directive. The following code shows the syntax to create a custom directive:

var myApplication = angular.module("<applicationName>",[]);
myApplication.directive("<directiveName>", function() {
    return {
        restrict: "<represent the usage of directive>",
  require:"<Dependent module>"
        scope: {
           //Scope variable declaration
        },
        template:"<HTML template string>",
        templateUrl:"<URL of the HTML template>",
        replace: "<Boolean value>",
        priority:"<Number value>",
        terminal:"<Boolean value>",
  transclude: "<Boolean value>",
        controller:  function ($scope, $element, $attrs){
            //Code for scope object and behavior
        },
        link: function (scope, element, attrs) {
            //Code for link phase
        }
    }
});

The details of the properties shown in the preceding code are as follows:

  • restrict: This property controls the use of the custom directive. A directive in AngularJS can be used as Attribute (A), Element (E), Class (C), and Comment (M). It can have the value of any combination of A, E, C, and M. An example of this attribute is as follows:

    restrict : "AC" 

    The preceding code designates the custom directive and can only be used as an attribute or a class. The default value of the restrict property is A if nothing is supplied to it.

  • require: This property is to inject other required directives or set of directives. It takes a string or array of strings of the directive name as an input.

  • scope: This property is very vital as it determines the current scope of the directive. It takes two types of values, either true or an unanimous JavaScript object {} with some attribute and values. Some uses of these properties are as follows:

    • true: This creates a new scope with access to the current parent scope(normal scope).

    • {}: This creates a new scope and separates it to the current scope without access to the parent directive scope (isolated scope). This object has the following attributes to configure: @, &, and =.

  • template: This property takes its value as an HTML markup string. This mark-up will be replaced/appended to the current element. An example of this attribute are as follows:

     template:"<h2>Hello</h2>"

    The preceding code designates a template string that will replace/append the current element.

  • templateUrl: This property is an alternative option for a template. This property accepts a URL value.

  • replace: This property takes a Boolean (true or false) value as an input. If it is true, it replaces the current element with the given template. If it is false, it appends the template to the current element, for example, replacing true designates that the current element will be removed and the template will be placed in that position.

  • priority: This property takes a number as a value. This property determines the execution order of directives. A higher value of priority implies that it will run first. The default value of priority for a directive is 0.

  • terminal: This property takes a Boolean (true or false) as the value. When this property is set to true, the directive will execute.

  • transclude: This property takes true or element as the value. Based on the input value, it compiles the current directive or elements and enables it to present a directive.

  • controller: This property is used as an initializer and can be used to pass values among directives. It has the following property access: $scope, $element, and $attr.

  • link: This property is used to write code to manipulate the DOM element inside the scope, for example, a click event listener callback can be written inside it.

Note

To find out more about creating custom directives, visit https://docs.angularjs.org/guide/directive.

 

Role of AngularJS


In this section, we will explore the role of AngularJS for responsive web development. Before going into AngularJS, you will learn about responsive web development in general. Responsive web development can be performed in two ways:

  • Using the browser sniffing approach

  • Using the CSS3 media queries approach

Using the browser sniffing approach

When we view web pages through our browser, the browser sends a user agent string to the server. This string provides information like browser and device details. Reading these details, the browser can be redirected to the appropriate view. This method of reading client details is known as browser sniffing.

The browser string has a lot of different information about the source from where the request is generated. The following diagram shows the information shared by the user string:

Details of the parameters present in the user agent string are as follows:

  • Browser name: This represents the actual name of the browser from where the request has originated, for example, Mozilla or Opera

  • Browser version: This represents the browser release version from the vendor, for example, Firefox has the latest version 31

  • Browser platform: This represents the underlying engine on which the browser is running, for example, Trident or WebKit

  • Device OS: This represents the operating system running on the device from where the request has originated, for example, Linux or Windows

  • Device processor: This represents the processor type on which the operating system is running, for example, 32 or 64 bit

A different browser string is generated based on the combination of the device and type of browser used while accessing a web page. The following table shows examples of browser strings:

Browser

Device

User agent string

Firefox

Windows desktop

Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0

Chrome

OS X 10

desktop

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36

Opera

Windows desktop

Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14

Safari

OS X 10

desktop

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.13+ (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2

Internet Explorer

Windows desktop

Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0

AngularJS has features like providers or services which can be most useful for this browser user-agent sniffing and a redirection approach. An AngularJS provider can be created that can be used in the configuration in the routing module. This provider can have reusable properties and reusable methods that can be used to identify the device and route the specific request to the appropriate template view.

Note

To discover more about user agent strings on various browser and device combinations, visit http://www.useragentstring.com/pages/Browserlist/.

CSS3 media queries approach

CSS3 brings a new horizon to web application development. One of the key features is media queries to develop a responsive web application. Media queries uses media types and features as deciding parameters to apply the style to the current web page.

Media type

CSS3 media queries provide rules for media types to have different styles applied to a web page. In the media queries specification, media types that should be supported by the implemented browser are listed. These media types are as follows:

  • all: This is used for all media type devices

  • aural: This is used for speech and sound synthesizers

  • braille: This is used for braille tactile feedback devices

  • embossed: This is used for paged braille printers

  • handheld: This is used for small or handheld devices, for example, mobile

  • print: This is used for printers, for example, an A4 size paper document

  • projection: This is used for projection-based devices, such as a projector screen with a slide

  • screen: This is used for computer screens, for example, desktop and laptop screens

  • tty: This is used for media using a fixed-pitch character grid, such as teletypes and terminals

  • tv: This is used for television-type devices, for example, webOS or Android-based television

A media rule can be declared using the @media keyword with the specific type for the targeted media. The following code shows an example of the media rule usage, where the background body color is black and text is white for the screen type media, and background body color is white and text is black for the printer media type:

@media screen {
  body {
    background:black;
    color:white;
  }
}

@media print{
  body {
    background:white;
    color:black;
  }
}

An external style sheet can be downloaded and applied to the current page based on the media type with the HTML link tag. The following code uses the link type in conjunction with media type:

<link rel='stylesheet' media='screen' href='<fileName.css>' />

Note

To learn more about different media types,visit https://developer.mozilla.org/en-US/docs/Web/CSS/@media#Media_types.

Media feature

Conditional styles can be applied to a page based on different features of a device. The features that are supported by CSS3 media queries to apply styles are as follows:

  • color: Based on the number of bits used for a color component by the device-specific style sheet, this can be applied to a page.

  • color-index: Based on the color look up, table styles can be applied to a page.

  • aspect-ratio: Based on the aspect ratio, display area style sheets can be applied to a page.

  • device-aspect-ratio: Based on the device aspect ratio, styles can be applied to a page.

  • device-height: Based on device height, styles can be applied to a page. This includes the entire screen.

  • device-width: Based on device width, styles can be applied to a page. This includes the entire screen.

  • grid: Based on the device type, bitmap or grid, styles can be applied to a page.

  • height: Based on the device rendering area height, styles can be used to a page.

  • monochrome: Based on the monochrome type, styles can be applied. This represents the number of bits used by the device in the grey scale.

  • orientation: Based on the viewport mode, landscape or portrait, styles can be applied to a page.

  • resolution: Based on the pixel density, styles can be applied to a page.

  • scan: Based on the scanning type used by the device for rendering, styles can be applied to a page.

  • width: Based on the device screen width, specific styles can be applied.

The following code shows some examples of CSS3 media queries using different device features for conditional styles used:

//for screen devices with a minimum aspect ratio 0.5
@media screen and (min-aspect-ratio: 1/2)
{
  img
  {
    height: 70px;
    width: 70px;
  }
}
//for all device in portrait viewport
@media all and (orientation: portrait)
{
  img
  {
    height: 100px;
    width: 200px;
  }
}
//For printer devices with a minimum resolution of 300dpi pixel density
@media print and (min-resolution: 300dpi)
{
  img
  {
    height: 600px;
    width: 400px;
  }
}

In this section, we will explore more about the screen width. We will explore how AngularJS can help you use CSS3 media queries for a responsive application development. There are huge number of devices with different screen sizes present on the market, so we will focus on the most commonly used devices. The following diagram shows the different screen sizes of most commonly used devices such as mobile, desktop, and tablet:

Note

To learn more about different media features, visit https://developer.mozilla.org/en-US/docs/Web/CSS/@media#Media_features.

 

What are we building?


In the following chapters, we will build a small responsive SPA to understand the helpful features of AngularJS. The plan of action to develop this application is as follows:

  • We are going to build a My Portfolio web application

  • This application is going to have different sections such as personal details, academics, skills, and experiences

  • We will maintain all the data in different JSON files and serve them with appropriate templates when the user clicks on these sections

  • We will explore how AngularJS makes this application responsive using browser sniffing-redirection, media queries, and a directive-based approach

 

Summary


In this chapter, you learned about responsive design and the SPA architecture. You now understand the role of the AngularJS library when developing a responsive application. We quickly went through all the important features of AngularJS with the coded syntax. In the next chapter, you will set up your AngularJS application and learn to create dynamic routing-based on the devices.

About the Author

  • Sandeep Kumar Patel

    Sandeep Kumar Patel is a senior web developer and the founder of www.tutorialsavvy.com, a programming blog that has been widely read since its inception in 2012. He has over 5 years of experience in object-oriented JavaScript and JSON-based web applications development. He is GATE-2005 Information Technology (IT) qualified and has a master's degree from VIT University, Vellore. You can get to know more about him by looking at his LinkedIn profile (http://www.linkedin.com/in/techblogger). He has received the DZone Most Valuable Blogger (MVB) award for technical publications related to web technologies. His article can be viewed at http://www.dzone.com/users/sandeepgiet. He has also received the Java Code Geeks (JCG) badge for a technical article published on the JGC website. His article can be viewed at http://www.javacodegeeks.com/author/sandeep-kumar-patel/.

    His other books are listed as follows:

    • Instant GSON
    • Responsive Web Design with AngularJS

    Browse publications by this author
Book Title
Access this book, plus 7,500 other titles for FREE
Access now